Replace 2 characters within a reversed string at once

时间:2018-07-24 10:07:02

标签: python string python-3.x

myString = "test (with (w)ords) swap"

reverse the string and swap ( with ) and ) with (

output: "paws (sdro(w) htiw) tset"

Is there a simple way to do this?

2 个答案:

答案 0 :(得分:8)

You could reverse the string via slicing and (for Python 3) use str.translate with the appropriate str.maketrans mapping:

>>> s = "test (with (w)ords) swap"
>>> s[::-1].translate(str.maketrans('()', ')('))
'paws (sdro(w) htiw) tset'

答案 1 :(得分:0)

此功能适用于python2:

from string import maketrans
reversed = myString[::-1].translate(maketrans(")(", "()"))

输出:

paws (sdro(w) htiw) tset