-2

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.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • Use a dummy character for the intermediate step: `"+1-2".replace("+","!").replace("-","+").replace("!","-")` – not_speshal Nov 05 '21 at 17:38
  • 2
    Indeed, replacing one thing with another and then replacing the other thing with the first will turn all instances into the first. You want `translate` instead. – tripleee Nov 05 '21 at 17:39
  • @tripleee Thanks, I didn't know that function for replacing characters. – Cardstdani Nov 05 '21 at 17:40

1 Answers1

2

Use str.translate:

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

Output:

-1+2-3-4+2+1
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Thank you for the solution, I didn't know the `translate()` function for `strings`, now it's working perfectly. – Cardstdani Nov 05 '21 at 17:45