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

def a(s="-1+2-3"):
    s = re.sub('[+-]', lambda match: '-' if match[0] == '+' else '+', s)
    return s

def b(s="-1+2-3"):
    PLUS = '+'
    MINUS = '-'
    swap = {ord(PLUS): ord(MINUS), ord(MINUS): ord(PLUS)}
    s = s.translate(swap)
    return s

def c(s="-1+2-3"):
    replacements = {"+": "-", "-": "+"}

    return ''.join([replacements[i] if i in replacements.keys() else i for i in s])


def d(s="-1+2-3"):
    return s.replace('+', 'x01').replace('-', '+').replace('x01', '-')

if __name__ == '__main__':
    a = timeit.timeit(a, number=100000) # a=0.20307550000000002
    b = timeit.timeit(b, number=100000) # b=0.08596850000000006
    c = timeit.timeit(c, number=100000) # c=0.12203799999999998
    d = timeit.timeit(d, number=100000) # d=0.033226100000000036
    print(f"{a=}n{b=}n{c=}n{d=}n")

Advertisement

Answer

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

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

Output:

'+1-2+3'
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement