如何用 while 循环反转句子

how to reverse a sentence with a while loop

对于一个赋值,我需要使用一个while循环来反转一个列表,但我做不到。

这是帮助我入门的示例代码:

sentence = raw_int ("   ")
length = len(sentence) # determines the length of the sentence (how many characters there are)
index = length - 1 #subtracts one from the length because we will be using indexes which start at zero rather than 1 like len

while... #while the index is greater than or equal to zero continue the loop
letter = sentence[index] #take the number from the index in the sentence and assigns it to the variable letter

我需要在我的解决方案中使用它。

因为这是一个作业,所以我不会给你完整的代码。但是我会给你两个'hints'。 1) 如果每个字符都是'flipped',则句子被反转。例如,'I ran fast'——要翻转这句话,先交换'I'和'f',然后交换space和's',依此类推。 2) 您可以使用如下语法:

Sentence[i], sentence[len(sentence)-i] = sentence[len(sentence)-i], Sentence[i]

这绝对足以让您继续前进。

sentence = raw_input("   ")
length = len(sentence)
index = length - 1
reversed_sentence = ''

while index >= 0:
    #letter is the last letter of the original sentence
    letter = sentence[index] 
    #make the first letter of the new sentence the last letter of the old sentence
    reversed_sentence += letter 
    #update the index so it now points to the second to last letter of the original sentence
    index = index - 1 

print reversed_sentence

你可以这样做:

new_sentence = list()
sentence = list(raw_input("   "))

while sentence:
    new_sentence.append(sentence.pop(-1))
else:
    sentence = ''.join(new_sentence)