【发布时间】:2020-05-30 10:23:20
【问题描述】:
所以我正在尝试创建一个程序,它可以接收句子并使长度为 5 或更长的单词反转。目前只是翻转最后一个符合条件的单词,不知道为什么。
userInput = "Hello this is a test sentence"
wordList = userInput.split()
for i in wordList:
if len(i) >= 5:
reversedWord = i[::-1]
print(reversedWord)
reversedSentence = userInput.replace(i, reversedWord)
print(reversedSentence)
不是输出“olleH,这是一个测试 ecnetnes”,而是输出“你好,这是一个测试 ecnetnes”
【问题讨论】:
-
你总是用原始字符串来替换。
-
Python有一个函数
reversed,这里使用起来可能比i[::-1]更清晰。将i替换为word可能也会使事情更清楚。 -
用有意义的名称
word替换i是个好主意。但是如果你使用reversed,你必须自己重建字符串(例如reversed_word = ''.join(reversed(word)))。 -
它可能看起来很糟糕,但表明你可以通过加入、拆分和列表理解来做很多事情:
print(' '.join([(word if len(word) < 5 else ''.join(reversed(word)) )for word in userInput.split(' ')]))x) -
@garglblarg 当然显而易见的解决方案是
print(' '.join((lambda x: x[::2*(len(word) < 5)-1])(word) for word in sentence.split()))
标签: python python-3.x python-2.7 loops iteration