Home > database >  pythonic way to replace two character in a string
pythonic way to replace two character in a string

Time:03-25

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")

CodePudding user response:

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

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

Output:

' 1-2 3'

CodePudding user response:

you can use a dictionary and a loop, so you can have any number of replacements in your dictionary.

s = "-1 2-3"
replacements = {" ":"-", "-":" "}

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


' 1-2 3'

CodePudding user response:

You should try:

s=s.replace(' ','\x01').replace('-',' ').replace('\x01','-')

It replaces all the ' ' by an unused character, and then replaces the '-' by ' ' and then replaces the "unused characters" by '-', effectivly swapping ' ' and '-'.

CodePudding user response:

You can use re.sub().

import re

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

CodePudding user response:

Many have already answered you, so I add this example for completeness using the map() function:

def replaceSymbol(s):
    res = s;
    if ' ' in s:
       res = '-'
    elif '-' in s:
        res = ' '
    return res
        
''.join(map(replaceSymbol, "-1 2-3"))

Output:

 1-2 3
  • Related