简体   繁体   English

TypeError:字符串索引必须是整数

[英]TypeError : string indices must be integers

I've returned to Python after a few years doing C code and I'm a little confused while training myself to get my Python coding habits back. 经过几年的C代码编写工作,我回到了Python。在训练自己恢复Python编码习惯的过程中,我有些困惑。

I've tried to run this little, very simple, piece of code but I keep getting a TypeError as described in the title. 我试图运行这段非常简单的代码,但是我一直收到标题中所述的TypeError。 I've searched a lot but cannot figure out what is the problem with this : 我已经搜索了很多,但无法弄清楚这是什么问题:

def toLower(pStr):

i = 0

for i in pStr:
    if ord(pStr[i]) >= 65 and ord(pStr[i]) <= 90:
        pStr[i] = chr(ord(pStr[i])+28)

return pStr

testStr = "TEST STRING"

print(toLower(testStr))

Considering that i is an integer, I don't understand why I get this error. 考虑到i是一个整数,我不明白为什么会收到此错误。 Maybe I think too much like i'm doing C IDK. 也许我觉得我好像在做C IDK。

You are iterating over the string, so each i is bound to a single character, not an integer. 您正在遍历字符串,因此每个i都绑定到单个字符, 而不是整数。 That's because Python for loops are Foreach constructs , unlike C. 那是因为Python for循环是Foreach构造 ,与C不同。

Just use that character directly, no need to index back into the string. 只需直接使用该字符,而无需索引回字符串。 Python strings are also immutable , so you can't replace characters in the string object. Python字符串也是不可变的 ,因此您不能替换字符串对象中的字符。 Build a new object: 新建一个对象:

def toLower(pStr):
    output = []
    for char in pStr:
        if ord(char) >= 65 and ord(char) <= 90:
            char = chr(ord(char)+28))
        output.append(char)
    return ''.join(output)

If you must generate an index for something, you'd generally use either the range() type to produce those for you, or use enumerate() to produce both an index and the value itself in a loop. 如果必须为某些内容生成索引,则通常可以使用range()类型为您生成索引,或者使用enumerate()在循环中生成索引值本身。

Also, note you don't need to set the for loop target name to a default before the loop unless you need to handle the case where the loop iterable is empty and you expect to use the target name after the loop. 另外,请注意,除非需要处理循环iterable为空并且希望在循环之后使用目标名称的情况,否则不需要在循环之前将for循环目标名称设置为默认值。 In other words, your i = 0 is entirely redundant. 换句话说,您的i = 0完全是多余的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM