Py学习  »  Python

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

Mohit • 3 年前 • 1487 次点击  
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

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128614
文章 [ 2 ]  |  最新文章 3 年前
Manuel Fedele
Reply   •   1 楼
Manuel Fedele    3 年前

我喜欢像蟒蛇一样的东西

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)
Abhyuday Vaish
Reply   •   2 楼
Abhyuday Vaish    3 年前

只需创建一个新的空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