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

时间:2014-01-03 15:50:29

标签: python python-2.7

我有这段代码:

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

输出:     geb dna nep,repap yub ll'I

但我希望输出如下:     g'eb dna nep r,epap yub llI

我该怎么做?

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:3)

也许是这样的:

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