Stripping everything but alphanumeric chars from a string in Python

前端 未结 11 1483
不思量自难忘°
不思量自难忘° 2020-11-22 10:52

What is the best way to strip all non alphanumeric characters from a string, using Python?

The solutions presented in the PHP variant of this question will probably

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 11:39

    Use the str.translate() method.

    Presuming you will be doing this often:

    (1) Once, create a string containing all the characters you wish to delete:

    delchars = ''.join(c for c in map(chr, range(256)) if not c.isalnum())
    

    (2) Whenever you want to scrunch a string:

    scrunched = s.translate(None, delchars)
    

    The setup cost probably compares favourably with re.compile; the marginal cost is way lower:

    C:\junk>\python26\python -mtimeit -s"import string;d=''.join(c for c in map(chr,range(256)) if not c.isalnum());s=string.printable" "s.translate(None,d)"
    100000 loops, best of 3: 2.04 usec per loop
    
    C:\junk>\python26\python -mtimeit -s"import re,string;s=string.printable;r=re.compile(r'[\W_]+')" "r.sub('',s)"
    100000 loops, best of 3: 7.34 usec per loop
    

    Note: Using string.printable as benchmark data gives the pattern '[\W_]+' an unfair advantage; all the non-alphanumeric characters are in one bunch ... in typical data there would be more than one substitution to do:

    C:\junk>\python26\python -c "import string; s = string.printable; print len(s),repr(s)"
    100 '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
    

    Here's what happens if you give re.sub a bit more work to do:

    C:\junk>\python26\python -mtimeit -s"d=''.join(c for c in map(chr,range(256)) if not c.isalnum());s='foo-'*25" "s.translate(None,d)"
    1000000 loops, best of 3: 1.97 usec per loop
    
    C:\junk>\python26\python -mtimeit -s"import re;s='foo-'*25;r=re.compile(r'[\W_]+')" "r.sub('',s)"
    10000 loops, best of 3: 26.4 usec per loop
    

提交回复
热议问题