开发者

python3: removing several chars from a string with a long chain of .replace().replace().replace()

I found this example on stack overflow. I understand it, but seems like a bit much for such a simple method concept... removing several chars from a string.

import string
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)

is there a builtin string method in python 3.1 to do something to the tune of:

s = "a,b,c,d,e,开发者_开发技巧f,g,h,i"
s = s.strip([",", "d", "h"])

instead of:

s = s.replace(",", "").replace("d", "").replace("h", "")


I don't agree that the example you found is over-complex. For your use case, that code would become:

s = ''.join(ch for ch in s if ch not in ",dh")

which seems pretty concise to me. However, there is an alternative, which is very slightly more concise and may be more efficient:

s = s.translate(str.maketrans("", "", ",dh"))

Disclaimer: I haven't actually tested this code since I don't have access to a Python 3.1 interpreter. The equivalent in Python 2.6 (which I have tested) is:

t = ''.join(chr(i) for i in range(256))
s = s.translate(t, ",dh")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜