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

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

Python Type Error: string indices must be integers

问题

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

  1. 抱歉我在这里可能有点不熟悉Python因为我刚刚从JavaScript过来我遇到了一个问题即运行一个字符串通过一个函数该函数旨在返回控制台的彩色文本
  2. File "d:\Dev\DiscordIdleBotPython\venv\ccolours.py", line 16, in colourDyn
  3. return(f'{colours[colour]}{text}{colours["CCLEAR"]}')
  4. ~~~~~~~^^^^^^^^
  5. TypeError: 字符串索引必须是整数而不是'str'
  6. coloursAvailable={
  7. "CCLEAR": '3[0m',
  8. "COGREEN": '[42m'
  9. }
  10. def colourDyn(text, colour):
  11. colours=coloursAvailable[colour]
  12. if colour not in colours: print('颜色未定义或不可用')
  13. print("函数通过颜色检查")
  14. 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

  1. File "d:\Dev\DiscordIdleBotPython\venv\ccolours.py", line 16, in colourDyn
  2. return(f'{colours[colour]}{text}{colours["CCLEAR"]}')
  3. ~~~~~~~^^^^^^^^
  4. TypeError: string indices must be integers, not 'str'
  5. coloursAvailable={
  6. "CCLEAR": '3[0m',
  7. "COGREEN": '[42m'
  8. }
  9. def colourDyn(text, colour):
  10. colours=coloursAvailable[colour]
  11. if colour not in colours: print('colour undefined or not available')
  12. print("function passed colour check")
  13. 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:

确定