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
x
27
27
1
def a(s="-1+2-3"):
2
s = re.sub('[+-]', lambda match: '-' if match[0] == '+' else '+', s)
3
return s
4
5
def b(s="-1+2-3"):
6
PLUS = '+'
7
MINUS = '-'
8
swap = {ord(PLUS): ord(MINUS), ord(MINUS): ord(PLUS)}
9
s = s.translate(swap)
10
return s
11
12
def c(s="-1+2-3"):
13
replacements = {"+": "-", "-": "+"}
14
15
return ''.join([replacements[i] if i in replacements.keys() else i for i in s])
16
17
18
def d(s="-1+2-3"):
19
return s.replace('+', 'x01').replace('-', '+').replace('x01', '-')
20
21
if __name__ == '__main__':
22
a = timeit.timeit(a, number=100000) # a=0.20307550000000002
23
b = timeit.timeit(b, number=100000) # b=0.08596850000000006
24
c = timeit.timeit(c, number=100000) # c=0.12203799999999998
25
d = timeit.timeit(d, number=100000) # d=0.033226100000000036
26
print(f"{a=}n{b=}n{c=}n{d=}n")
27
Advertisement
Answer
You can use translate (without ord
as pointed out by Barmar):
JavaScript
1
3
1
s = "-1+2-3"
2
s.translate(str.maketrans('-+', '+-'))
3
Output:
JavaScript
1
2
1
'+1-2+3'
2