OK 400
OK 400

Reputation: 831

Replacing multiple characters at once

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(["_", ":", ","], "")

Upvotes: 5

Views: 6967

Answers (5)

Lucas Meier
Lucas Meier

Reputation: 449

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,"_:,")

Upvotes: 1

japan
japan

Reputation: 44

You should use regex for such kind of operations

import re

s = "foo_faa:fee,fii"

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

Upvotes: 1

mitch_
mitch_

Reputation: 1436

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.

Upvotes: 11

Ersel Er
Ersel Er

Reputation: 771

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

Upvotes: 1

AKX
AKX

Reputation: 168834

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'

Upvotes: 7

Related Questions