How to switch arithmetric operations in a String

Advertisements

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:

"+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

Leave a Reply Cancel reply