16

Is there a pythonic way to do what the str.strip() method does, except for all occurrences, not just those at the beginning and end of a string?

Example:

>> '::2012-05-14 18:10:20.856000::'.strip(' -.:')
>> '2012-05-14 18:10:20.856000'

I want

>> '::2012-05-14 18:10:20.856000::'.crazy_function(' -.:')
>> '20120514181020856000'

Does Python provides me a built-in crazy_function???

I could easily do it programatically, but I want to know if there is a built-in for that. Couldn't find one. Thank you for your help.

4

3 回答 3

23

使用该translate功能删除不需要的字符:

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

确保您的字符串是strtype 而不是unicode,因为函数的参数不会相同。对于 unicode,使用以下语法;它包括从要删除的字符中构建 unicode 序数的字典并将它们映射到None

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

与 进行性能比较的一些时间安排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
于 2012-05-14T21:30:19.480 回答
4

你可以很容易地做到这一点re.sub

>>> import re
>>> re.sub(r"[ -.:]", r"", "'::2012-05-14 18:10:20.856000::'")
'20120514181020856000'
>>> 
于 2012-05-14T21:30:54.133 回答
2

不,我认为没有内置的。

我会这样做:

>>> s = '::2012-05-14 18:10:20.856000::'
>>> 
>>> ''.join(x for x in s if x not in ' -.:')
'20120514181020856000'
>>> 
于 2012-05-14T21:32:06.470 回答