Skip to content
Advertisement

pythonic way to replace two character in a string

I have a string ,for example s = "-1+2-3" I want to replace all - to + and all + to -.

what I expected is s = +1-2+3 .So I can’t just use s.replace('-','+').replace('+','-'),because it return s=-1-2-3,maybe a for loop can help. But I wonder if there is a pythonic way to do so?

thanks for all solutions i did a simple test for all function below

JavaScript

Advertisement

Answer

You can use translate (without ord as pointed out by Barmar):

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement