我写了一个程序来反转给定句子中的单词:
def rev_each_word_in(Sentence):
print(' '.join(Word[::-1] for Word in Sentence.split()))
作为我对 Sentence 的输入,我使用了“to be or not to be that is the question”。这将返回以下内容:
ot eb ro ton ot eb taht si eht .noitseuq
这几乎正是我想要的,但是有没有办法让句点保留在句子的末尾,所以返回将是:
ot eb ro ton ot eb taht si eht noitseuq.
最佳答案
这里有一些丑陋的东西可以在一行中解决这个问题:
from string import punctuation as p
print(' '.join(w[::-1] if w[-1] not in p else w[:-1][::-1] + w[-1] for w in Sentence.split()))
如果单词中的最后一个字符不在标点符号字符串中,我们将完全反转,如果是,我们将字符串向上反转直到标点符号,然后将标点符号添加到它。打印出来:
ot eb ro ton ot eb taht si eht noitseuq.
尽可能地瘦下来,因为我为此感到羞耻:
# similar to [::-1]
r = slice(None, None,-1)
# cut down chars!
l = Sentence.split()
# reverse condition too and use shorter names
print(' '.join(w[:-1][r] + w[-1] if w[-1] in p else w[r] for w in l))
关于python - 反转 Python 字符串中的单词(包括标点符号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40698769/