Python语句反转

2024-04-19 12:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python创建一个程序,用户在其中输入一个句子并打印出相反的句子。到目前为止,我掌握的代码是:

sentence = raw_input('Enter the sentence')
length = len(sentence)

for i in sentence[length:0:-1]:
    a = i
    print a,

当程序运行时,它会漏掉最后一个字母,所以如果单词是“hello”,它会打印“olle”。有人能看出我的错误吗?你知道吗


Tags: the代码用户in程序程序运行forinput
3条回答

切片表示法的第二个参数表示“最多,但不包括”,因此sentence[length:0:-1]将循环到0,但不在0处。你知道吗

解决方法是显式地将0更改为-1,或者忽略它(首选)。你知道吗

for i in sentence[::-1]:

试试这个:使用MAP函数没有循环

mySentence = "Mary had a little lamb"

def reverseSentence(text):
     # split the text
     listOfWords = text.split()

     #reverese words order inside sentence
     listOfWords.reverse()

     #reverse each word inside the list using map function(Better than doing loops...)
     listOfWords = list(map(lambda x: x[::-1], listOfWords))

     #return
     return listOfWords

print(reverseSentence(mySentence))

您需要从索引范围中删除0,但可以使用:

sentence[length::-1]

也不是说你不需要循环你的字符串和使用额外的赋值,甚至length你也可以简单地打印反转的字符串。你知道吗

因此,以下代码将为您完成这项工作:

print sentence[::-1]

演示:

>>> s="hello"
>>> print s[::-1]
'olleh'

相关问题 更多 >