![Creative The name of the picture]()
Replace 2 characters within a reversed string at once
myString = "test (with (w)ords) swap"
reverse the string and swap ( with ) and ) with (
output: "paws (sdro(w) htiw) tset"
"paws (sdro(w) htiw) tset"
Is there a simple way to do this?
2 Answers
2
You could reverse the string via slicing and (for Python 3) use str.translate
with the appropriate str.maketrans
mapping:
str.translate
str.maketrans
>>> s = "test (with (w)ords) swap"
>>> s[::-1].translate(str.maketrans('()', ')('))
'paws (sdro(w) htiw) tset'
This work for python2:
from string import maketrans
reversed = myString[::-1].translate(maketrans(")(", "()"))
Output:
paws (sdro(w) htiw) tset
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
all there... forgot it when typing it in
– Dominik Lemberger
5 hours ago