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
我喜欢像这样的蟒蛇
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)