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
How about:
>>> string_1 = "(555).555-5555"
>>> string_2 = "(555) 555 - 5555 ext. 5555"
>>> any(c.isalpha() for c in string_1)
False
>>> any(c.isalpha() for c in string_2)
True
Regex should be a fast approach:
re.search('[a-zA-Z]', the_string)
I liked the answer provided by @jean-françois-fabre, but it is incomplete.
His approach will work, but only if the text contains purely lower- or uppercase letters:
>>> text = "(555).555-5555 extA. 5555"
>>> text.islower()
False
>>> text.isupper()
False
The better approach is to first upper- or lowercase your string and then check.
>>> string1 = "(555).555-5555 extA. 5555"
>>> string2 = '555 (234) - 123.32 21'
>>> string1.upper().isupper()
True
>>> string2.upper().isupper()
False
You can also do this in addition
import re
string='24234ww'
val = re.search('[a-zA-Z]+',string)
val[0].isalpha() # returns True if the variable is an alphabet
print(val[0]) # this will print the first instance of the matching value
Also note that if variable val returns None. That means the search did not find a match
You can use islower()
on your string to see if it contains some lowercase letters (amongst other characters). or
it with isupper()
to also check if contains some uppercase letters:
below: letters in the string: test yields true
>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True
below: no letters in the string: test yields false.
>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>>
Not to be mixed up with isalpha()
which returns True
only if all characters are letters, which isn't what you want.
Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.
You can use regular expression like this:
import re
print re.search('[a-zA-Z]+',string)