python str对象不支持项目赋值
python str object does not support item assignment
我正在尝试将列表中的乱序词设置回我创建的列表,该列表来自 split
。我尝试阅读此处的一些解决方案,我认为这是因为您无法更改列表中的字符串?
如果我错了,我不确定是否纠正我:(。the sentence[i] = temp_word
给出了错误。提前致谢:)
class WordScramble:
def __init__(self):
self.user_input = input("Please give me a sentence: ")
def scramble(self):
# print what was input
print("The user input was: ", self.user_input)
# first scramble is just one word
print(self.user_input[0] + self.user_input[2] + self.user_input[1] + self.user_input[3:])
# reverse two indices
# particularly good to use is to switch the first two
# and the last two
# this only makes sense if you have a world that is longer than 3
# now try to scramble one sentence
sentence = self.user_input.strip().split(" ")
for i, word in enumerate(sentence):
if len(word) > 3:
temp_word = list(word)
if ',' in temp_word:
temp = temp_word[1]
temp_word[1] = temp_word[-3]
temp_word[-3] = temp
else:
temp = temp_word[1]
temp_word[1] = temp_word[2]
temp_word[2] = temp
temp_word = ''.join(temp_word)
sentence[i] = temp_word
sentence = ''.join(sentence)
print(sentence)
#print(" ".join(sentence))
# do just words first, then you can move on to work on
# punctuation
word_scrambler = WordScramble()
word_scrambler.scramble()
因为在 for 循环中你写了:
sentence = ''.join(sentence)
因此,在第二次迭代中,'sentence' 变量现在是一个字符串,而在 python 中,字符串不支持项目分配,因为它们是不可变变量。我认为你的意思是将它从 for 循环中取出来打印最后一句话。
我正在尝试将列表中的乱序词设置回我创建的列表,该列表来自 split
。我尝试阅读此处的一些解决方案,我认为这是因为您无法更改列表中的字符串?
如果我错了,我不确定是否纠正我:(。the sentence[i] = temp_word
给出了错误。提前致谢:)
class WordScramble:
def __init__(self):
self.user_input = input("Please give me a sentence: ")
def scramble(self):
# print what was input
print("The user input was: ", self.user_input)
# first scramble is just one word
print(self.user_input[0] + self.user_input[2] + self.user_input[1] + self.user_input[3:])
# reverse two indices
# particularly good to use is to switch the first two
# and the last two
# this only makes sense if you have a world that is longer than 3
# now try to scramble one sentence
sentence = self.user_input.strip().split(" ")
for i, word in enumerate(sentence):
if len(word) > 3:
temp_word = list(word)
if ',' in temp_word:
temp = temp_word[1]
temp_word[1] = temp_word[-3]
temp_word[-3] = temp
else:
temp = temp_word[1]
temp_word[1] = temp_word[2]
temp_word[2] = temp
temp_word = ''.join(temp_word)
sentence[i] = temp_word
sentence = ''.join(sentence)
print(sentence)
#print(" ".join(sentence))
# do just words first, then you can move on to work on
# punctuation
word_scrambler = WordScramble()
word_scrambler.scramble()
因为在 for 循环中你写了:
sentence = ''.join(sentence)
因此,在第二次迭代中,'sentence' 变量现在是一个字符串,而在 python 中,字符串不支持项目分配,因为它们是不可变变量。我认为你的意思是将它从 for 循环中取出来打印最后一句话。