+ 2

Symbol replacement in python

There's a string: a = 's+4-3' I need to replace (invert) + with - and - with + to get: 's-4+3' What is the way of doing that?

26th Feb 2017, 5:06 PM
Vaas
Vaas - avatar
2 Answers
+ 7
print(a.replace('+','.').replace('-','+').replace('.','-'))
26th Feb 2017, 6:11 PM
Senfman
Senfman - avatar
+ 4
Now with two additional realisations. I, personally, like the dictionary variation pretty much as it is most flexible with minimal effort for extension: a = 's+4-3' print("Original string: %s" % (a)) swap_a = a.replace('+','.').replace('-','+').replace('.','-') print("String after swapping operators, procedure (1): %s" % (swap_a)) swap_b = "" for char in a: if char == '+': swap_b += '-' elif char == '-': swap_b += '+' else: swap_b += char print("String after swapping operators, procedure (2): %s" % (swap_b)) swapDict = {'+': '-','-': '+'} swap_c = ''.join(swapDict[char] if char in swapDict else char for char in a) print("String after swapping operators, procedure (3): %s" % (swap_c))
27th Feb 2017, 6:55 AM
Senfman
Senfman - avatar