How to check if a string contains any letters from the alphabet?

What is the 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 will return False for the absence of the letters of the alphabet in it, and string_2 will return True for the letter.

+58
python string
Jan 31 2018-12-01T00:
source share
6 answers

Regex should be a quick approach:

 re.search('[a-zA-Z]', the_string) 
+96
Jan 31 2018-12-12T00: 00Z
source share
— -

What 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 
+57
Jan 31 2018-12-12T00:
source share

You can use islower() in your string to see if it contains several lowercase letters (among other characters). or using isupper() to also check if some uppercase letters contain:

below: letters in a string: test returns true

 >>> z = "(555) 555 - 5555 ext. 5555" >>> z.isupper() or z.islower() True 

below: there are no letters in the line: test returns false.

 >>> z= "(555).555-5555" >>> z.isupper() or z.islower() False >>> 

Not to be confused with isalpha() which returns True only if all characters are letters, and this is not what you need.

Please note that Barma’s answer complements mine well, as mine does poorly with the mixed case.

+17
Mar 24 '17 at 15:08
source share

You can use regex as follows:

 import re print re.search('[a-zA-Z]+',string) 
+8
Jan 31 '12 at
source share

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 capital letters:

 >>> text = "(555).555-5555 extA. 5555" >>> text.islower() False >>> text.isupper() False 

The best approach is to first upper- or lowercase, and then check.

 >>> string1 = "(555).555-5555 extA. 5555" >>> string2 = '555 (234) - 123.32 21' >>> string1.upper().isupper() True >>> string2.upper().isupper() False 
+6
Nov 23 '17 at 10:40
source share

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 the variable val returns None. This means that the search did not find a match.

0
Apr 12 '18 at 13:18
source share



All Articles