Python类型错误:字符串索引必须是整数。

huangapple go评论177阅读模式
英文:

Python Type Error: string indices must be integers

问题

抱歉,以下是您提供的代码的翻译部分:

抱歉我在这里可能有点不熟悉Python因为我刚刚从JavaScript过来我遇到了一个问题即运行一个字符串通过一个函数该函数旨在返回控制台的彩色文本

File "d:\Dev\DiscordIdleBotPython\venv\ccolours.py", line 16, in colourDyn
    return(f'{colours[colour]}{text}{colours["CCLEAR"]}')
              ~~~~~~~^^^^^^^^
TypeError: 字符串索引必须是整数而不是'str'

coloursAvailable={
  "CCLEAR": '3[0m',
  "COGREEN": '[42m'
  }
def colourDyn(text, colour):
  colours=coloursAvailable[colour]

  if colour not in colours: print('颜色未定义或不可用')
  
  print("函数通过颜色检查")
  return(f'{colours[colour]}{text}{colours["CCLEAR"]}')
英文:

So forgive me a little here as im new to python just coming over from JS im having an issue running a string through a function which is meant to return a coloured text for console

File "d:\Dev\DiscordIdleBotPython\venv\ccolours.py", line 16, in colourDyn
    return(f'{colours[colour]}{text}{colours["CCLEAR"]}')
              ~~~~~~~^^^^^^^^
TypeError: string indices must be integers, not 'str'

coloursAvailable={
  "CCLEAR": '3[0m',
  "COGREEN": '[42m'
  }
def colourDyn(text, colour):
  colours=coloursAvailable[colour]

  if colour not in colours: print('colour undefined or not available')
  
  print("function passed colour check")
  return(f'{colours[colour]}{text}{colours["CCLEAR"]}')

Im clearly formatting something wrong but i don't know where perhaps im not even searching the array correctly?

any help appreciated

答案1

得分: 2

尝试在colourDyn的第一行中使用colours=coloursAvailable

目前,您已经从coloursAvailable中获取颜色,因此出现错误。

英文:

Try colours=coloursAvailable in the first line of colourDyn.

Currently, you are already getting the colour from coloursAvailable, thus the error.

答案2

得分: 1

看起来重新分配了颜色的值为特定颜色,如下所示:
colours=coloursAvailable[colour],所以当您稍后尝试索引颜色时,它已经被重新分配为coloursAvailable[colour]是什么。

如其他答案中建议的,您可以通过改为执行colours=coloursAvailable或者只删除该行并直接使用coloursAvailable来修复。

英文:

It looks like reassigned the value of colour to be a particular colour here:
colours=coloursAvailable[colour] so when you later try to index colours, it's already been reassigned to whatever coloursAvailable[colour] is.

As suggested in the other answer, you can fix by instead doing colours=coloursAvailable or just delete that line and use coloursAvailable directly.

huangapple
  • 本文由 发表于 2023年7月28日 05:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定