How can I check if a string contains ANY letters from the alphabet?

前端 未结 7 1637
我在风中等你
我在风中等你 2020-11-29 19:09

What is best pure Python implementation to check if a string contains ANY letters from the alphabet?

string_1 = \"(555).555-5555\"
string_2 = \"(555) 555 - 5         


        
相关标签:
7条回答
  • 2020-11-29 20:09

    I tested each of the above methods for finding if any alphabets are contained in a given string and found out average processing time per string on a standard computer.

    ~250 ns for

    import re
    

    ~3 µs for

    re.search('[a-zA-Z]', string)
    

    ~6 µs for

    any(c.isalpha() for c in string)
    

    ~850 ns for

    string.upper().isupper()
    


    Opposite to as alleged, importing re takes negligible time, and searching with re takes just about half time as compared to iterating isalpha() even for a relatively small string.
    Hence for larger strings and greater counts, re would be significantly more efficient.

    But converting string to a case and checking case (i.e. any of upper().isupper() or lower().islower() ) wins here. In every loop it is significantly faster than re.search() and it doesn't even require any additional imports.

    0 讨论(0)
提交回复
热议问题