从Python的字符串中剥离除字母数字字符外的所有内容

发布于 2021-02-02 23:16:09

使用Python从字符串中剥离所有非字母数字字符的最佳方法是什么?

这个问题的PHP变体中提供的解决方案可能会进行一些小的调整,但对我来说似乎并不是很“ pythonic”。

作为记录,我不仅要删除句点和逗号(以及其他标点符号),还希望删除引号,方括号等。

关注者
0
被浏览
94
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    使用Python从字符串中剥离所有非字母数字字符的最佳方法是什么?

    这个问题的PHP变体中提供的解决方案可能会进行一些小的调整,但对我来说似乎并不是很“ pythonic”。

    作为记录,我不仅要删除句点和逗号(以及其他标点符号),还希望删除引号,方括号等。我只是出于好奇而对某些功能进行了计时。在这些测试中,我从字符串string.printable(内置string模块的一部分)中删除了非字母数字字符。发现使用编译'[\W_]+'和pattern.sub('', str)最快。

    $ python -m timeit -s \
         "import string" \
         "''.join(ch for ch in string.printable if ch.isalnum())" 
    10000 loops, best of 3: 57.6 usec per loop
    
    $ python -m timeit -s \
        "import string" \
        "filter(str.isalnum, string.printable)"                 
    10000 loops, best of 3: 37.9 usec per loop
    
    $ python -m timeit -s \
        "import re, string" \
        "re.sub('[\W_]', '', string.printable)"
    10000 loops, best of 3: 27.5 usec per loop
    
    $ python -m timeit -s \
        "import re, string" \
        "re.sub('[\W_]+', '', string.printable)"                
    100000 loops, best of 3: 15 usec per loop
    
    $ python -m timeit -s \
        "import re, string; pattern = re.compile('[\W_]+')" \
        "pattern.sub('', string.printable)" 
    100000 loops, best of 3: 11.2 usec per loop
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看