我试图在python中创建一个程序,其中用户输入一个句子,并打印反判。到目前为止我的代码是:
sentence = raw_input('Enter the sentence')
length = len(sentence)
for i in sentence[length:0:-1]:
a = i
print a,
当程序运行时,它遗漏了最后一个字母,所以如果单词是'hello',它将打印'olle'。有人能看出我的错误吗?
您需要从索引范围中删除0
,但您可以使用:
sentence[length::-1]
也不是说,然后你不需要循环你的字符串,使用额外的赋值,甚至length
,你可以简单地打印反向字符串。
那么下面的代码将为您完成这项工作:
print sentence[::-1]
演示:>>> s="hello"
>>> print s[::-1]
'olleh'
Try This: NO LOOPS using MAP Function
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))
切片符号的第二个参数表示"up to,但不包括",因此sentence[length:0:-1]
将循环到0,但不是0。
修复方法是显式地将0更改为-1,或者将其省略(首选)。
for i in sentence[::-1]:
print ''.join(reversed(raw_input('Enter the sentence')))
给你:
sentence = raw_input('Enter the sentence')
length = len(sentence)
sentence = sentence[::-1]
print(sentence)
享受吧!
解释一下,重要的sentence = sentence[::-1]
行使用了Python的切片表示法。在这里详细介绍。
这种语法的利用反转了可迭代字符串中项的索引。结果是你想要的相反的句子。