我有:
LETTERS = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
results = ['BAN', 'ANA', 'PEE', 'L']
length = len(LETTERS)
for segment in results:
# get the numerical position of the character
first_char = LETTERS.index(segment[0])
# get the shift number
first_char = (first_char + 0) % length
#first character shift
segment[0] = LETTERS[first_char]
我收到如下错误:
segment[0] = LETTERS[first_char]
TypeError: 'str' object does not support item assignment
如果我修改这个程序,使它不在for循环中,它可以工作,但在循环中是我得到消息的地方。那是为什么?
答案 0 :(得分:0)
你正在使用foreach
种循环。
for segment in results:
段是数组中的项目,您无法将其编入索引(就像您执行segment[0]
)。
答案 1 :(得分:0)
字符串是不可变的,因此您无法分配索引。
您可以创建一个像这样的新字符串
segment = LETTERS[first_char] + segment[1:]
但这不会取代结果中的价值。要做到这一点,你需要枚举
for i, segment in enumerate(results):
...
result[i] = LETTERS[first_char] + segment[1:]
答案 2 :(得分:0)
您需要创建一个新字符串并替换旧字符串,而不是更改(不可变)字符串:
LETTERS = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
results = ['BAN', 'ANA', 'PEE', 'L']
length = len(LETTERS)
for i in range(len(results)):
# get the numerical position of the character
first_char = LETTERS.index(results[i][0])
# get the shift number
first_char = (first_char + 0) % length
#first character shift
results[i] = LETTERS[first_char] + results[i][1:]