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?
答案 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