Replace 2 characters within a reversed string at once

Multi tool use
Multi tool use
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?





all there... forgot it when typing it in
– Dominik Lemberger
5 hours ago




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.

RFD8,4eYRPs5qSa VvZj ozQ936B,BJ4hirWvWOShfXjZ,LIli vL3WEvrCyOcWYS5 Xl51IbNVUtTLXwsh58,aaQz3xGBY
QHqHM7celb9nJWk prvhZLN6oHV5c7,vHgbBoylxwhy61LnVLFJTqLTkzHXUx

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

415 Unsupported Media Type while sending json file over REST Template