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
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.