如何在不改变单词位置的情况下反转 python 中的字符串?

how to reverse a string in python without changing the position of words?

str5 = 'peter piper picked a peck of pickled peppers.'
b = str5.split()
for i in b:
    print(i[::-1])

#输出:

retep
repip
dekcip
a
kcep
fo
delkcip
.sreppep

我应该怎么做才能让它看起来像一行?

只需创建一个新的空 str 变量并将其连接即可。

str5 = 'peter piper picked a peck of pickled peppers.'
b = str5.split()
rev_str5 = ""
for i in b:
    rev_str5 = rev_str5 + ' ' + i[::-1]
print(rev_str5.lstrip()) # Removes the one space in the starting.

这里还有一个更短的方法。感谢评论:

str5 = 'peter piper picked a peck of pickled peppers.'    
print(' '.join(w[::-1] for w in str5.split()))

输出:

retep repip dekcip a kcep fo delkcip .sreppep

我喜欢像 pythonic 这样的东西

phrase = "peter piper picked a peck of pickled peppers."
reversed_word_list = [word[::-1] for word in phrase.split()]
reversed_phrase = " ".join(reversed_word_list)