如何在字符串中反转位置?

2024-10-04 09:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

a = "I'll buy paper,pen and beg"
print a[::-1]

输出: geb dna nep,准备好

但我希望输出是这样的: g'eb dna nep r,epap yub llI公司

我该怎么做?你知道吗


Tags: and密码buydnapaperprintlleb
2条回答

可能是这样的:

targets = ".,'"
a = "I'll buy paper,pen and beg"
punct = [ (i, c) for i, c in enumerate (a) if c in targets]
nopunct = [c for c in a if c not in targets][::-1]
for i, c in punct: nopunct.insert (i, c)
b = ''.join (nopunct)
print (a)
print (b)

这个指纹

g'eb dna nepre,pap yub llI
I'll buy paper,pen and beg

或者将目标更改为只打印.,

geb dna neprep,ap yub ll'I
I'll buy paper,pen and beg

使用反向字符串并构建一个只包含字母字符的生成器。然后用它作为替换字母字符的来源:

s = "I'll buy paper,pen and beg"
rev = (ch for ch in reversed(s) if ch.isalpha())
new = ''.join(next(rev) if ch.isalpha() else ch for ch in s)
# g'eb dna nepre,pap yub llI

相关问题 更多 >