Remove all occurrences of several chars from a string

╄→尐↘猪︶ㄣ 提交于 2019-12-04 23:05:13

Use the translate function to delete the unwanted characters:

>>> '::2012-05-14 18:10:20.856000::'.translate(None, ' -.:')
'20120514181020856000'

Be sure your string is of str type and not unicode, as the parameters of the function won't be the same. For unicode, use the following syntax ; it consists in building the dict of unicode ordinals from the chars to delete and to map them to None:

>>> u'::2012-05-14 18:10:20.856000::'.translate({ord(k):None for k in u' -.:'})
u'20120514181020856000'

Some timings for performance comparison with re:

>>> timeit.timeit("""re.sub(r"[ -.:]", r"", "'::2012-05-14 18:10:20.856000::'")""","import re")
7.352270301875713
>>> timeit.timeit("""'::2012-05-14 18:10:20.856000::'.translate(None, ' -.:')""")
0.5894893344550951

You could do it easily enough with re.sub

>>> import re
>>> re.sub(r"[ -.:]", r"", "'::2012-05-14 18:10:20.856000::'")
'20120514181020856000'
>>> 

No. I don't think there is a built in.

I would do it this way:

>>> s = '::2012-05-14 18:10:20.856000::'
>>> 
>>> ''.join(x for x in s if x not in ' -.:')
'20120514181020856000'
>>> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!