简体   繁体   English

一次替换多个字符

[英]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() )就像(使用str.replace()

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

An option that requires no looping or regular expressions is translate :不需要循环或正则表达式的选项是translate

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

Note that for Python 2, the API is slightly different .请注意,对于 Python 2,API 略有不同

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.不直接使用replace ,但您可以为这些字符构建一个带有字符类的正则表达式,并一次替换所有这些字符。 This is likely to be more efficient than a loop, too.这也可能比循环更有效。

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

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

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):或者使用string.translate (使用 Python 2):

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

You should use regex for such kind of operations您应该使用正则表达式进行此类操作

import re

s = "foo_faa:fee,fii"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM