How can I check if a string contains ANY letters from the alphabet?
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 - 5555 ext. 5555
Where string_1
would return False
for having no letters of the alphabet in it and string_2
would return True
for having letter.
Regex should be a fast approach:
re.search('[a-zA-Z]', the_string)
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
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.