Python 如何反转字符串中的位置?

Python 如何反转字符串中的位置?,python,python-2.7,Python,Python 2.7,我有以下代码: a = "I'll buy paper,pen and beg" print a[::-1] 输出: geb dna nep,准备好了 但我希望输出是这样的: g'eb dna nep r,epap yub llI 我该怎么做呢?可能是这样的: targets = ".,'" a = "I'll buy paper,pen and beg" punct = [ (i, c) for i, c in enumerate (a) if c in targets] nopunct =

我有以下代码:

a = "I'll buy paper,pen and beg"
print a[::-1]
输出: geb dna nep,准备好了

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

我该怎么做呢?

可能是这样的:

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

换句话说,您希望反转字母和空格字符,而不是标点符号?为什么示例中的
g'eb
ll'I
中都应该有撇号?您希望的输出有两个撇号。另一个是从哪里来的?@kojiro我想反转字符串,但保留标点符号的索引。抱歉,只是键入错误@LittleBobbyTables。您可以使用
targets=string.标点符号
获取所有punctuation@jonrsharpe很好的输入。让我们把这个留给OP来决定。@jonrsharpe怎么做?
导入字符串
,然后
目标=字符串。标点符号
<代码>字符串。标点符号=='!“#$%&\'()*+,-./:;?@[\]^ `{{124;}~'
@jornsharpe或仅从字符串导入标点符号作为目标