英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论