Home > front end >  Replacing multiple characters at once
Replacing multiple characters at once

Time:07-13

Is there any way to replace multiple characters in a string at once, so that instead of doing:

"foo_faa:fee,fii".replace("_", "").replace(":", "").replace(",", "")

just something like (with str.replace())

"foo_faa:fee,fii".replace(["_", ":", ","], "")

CodePudding user response:

An option that requires no looping or regular expressions is translate:

>>> "foo_faa:fee,fii".translate(str.maketrans('', '', "_:,"))
"foofaafeefii"

Note that for Python 2, the API is slightly different.

CodePudding user response:

Not directly with replace, but you can build a regular expression with a character class for those characters and substitute all of them at once. This is likely to be more efficient than a loop, too.

>>> import re
>>> re.sub(r"[_:,] ", "", "foo_faa:fee,fii")
'foofaafeefii'

CodePudding user response:

You can try with a loop:

replace_list = ["_", ":", ","]
my_str = "foo_faa:fee,fii"
for i in replace_list:
    my_str = my_str.replace(i, "")

CodePudding user response:

If your only goal is to replace the characters by "", you could try:

''.join(c for c in "foo_faa:fee,fii" if c not in ['_',':',','])

Or alternatively using string.translate (with Python 2):

"foo_faa:fee,fii".translate(None,"_:,")

CodePudding user response:

You should use regex for such kind of operations

import re

s = "foo_faa:fee,fii"

print(re.sub("_*|:*|,*", "", s))
  • Related