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

前端 未结 7 1636
我在风中等你
我在风中等你 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 19:47

    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
    
    0 讨论(0)
  • 2020-11-29 19:52

    Regex should be a fast approach:

    re.search('[a-zA-Z]', the_string)
    
    0 讨论(0)
  • 2020-11-29 19:56

    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
    
    0 讨论(0)
  • 2020-11-29 19:56

    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

    0 讨论(0)
  • 2020-11-29 19:57

    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.

    0 讨论(0)
  • 2020-11-29 20:00

    You can use regular expression like this:

    import re
    
    print re.search('[a-zA-Z]+',string)
    
    0 讨论(0)
提交回复
热议问题