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")
精彩评论