python - 反转 Python 字符串中的单词(包括标点符号)

标签 python string python-3.x

我写了一个程序来反转给定句子中的单词:

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/

相关文章:

c# - 将 XmlNodeList 转换为 List<string>

python - numpy 中的二进制编码的十进制 dtype

python - 如何在 pandas 的数据框中对数据进行装箱

python - C 扩展中的函数随机停止 python 程序执行

python - Django 静态文件相对引用 Amazon S3

mysql - 使用python从mysql字符串中搜索关键字?

string - 输入不完整的strsplit成data.frame

python - 模型中具有不同名称的 Django 模型属性和数据库字段

python - Python 3 中的排序函数

python - Python 中 '' 和 ""的区别