объект python str не поддерживает назначение элементов - PullRequest
0 голосов
/ 16 октября 2019

Я пытаюсь установить зашифрованное слово из списка обратно в список, который я создал, то есть из 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()

1 Ответ

1 голос
/ 16 октября 2019

Поскольку внутри цикла for вы написали:

sentence = ''.join(sentence)

Таким образом, на второй итерации переменная 'Предложение' теперь является строкой, а в Python строки не поддерживают присвоение элементов, поскольку онинеизменяемые переменные. Я думаю, что вы хотели убрать это из цикла for, чтобы напечатать последнее предложение.

...