Replace 2 characters within a reversed string at once

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.

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?

How to scale/resize CVPixelBufferRef in objective C, iOS