Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to switch arithmetric operations in a String

I have a problem when trying to switch the signs of all arithmetic operations inside a string in Python.

My input looks like this: "+1-2"

And the output should be something like that: "-1+2"

But when I try to replace the characters with replace() function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"+1-2".replace("+", "-").replace("-", "+")

The output I get is that: '+1+2'

Looks like the replace functions are replacing everything at the same time, so it will never switch it correctly in that way. A one-liner solution with similar functions would be very helpful.

>Solution :

Use str.translate:

s = "+1-2+3+4-2-1"
t = str.maketrans('+-','-+')
print(s.translate(t))

Output:

-1+2-3-4+2+1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading