简体   繁体   中英

How can I check if a string only contains uppercase or lowercase letters?

Return True if and only if there is at least one alphabetic character in s and the alphabetic characters in s are either all uppercase or all lowercase.

def upper_lower(s):

   """ (str) -> bool



>>> upper_lower('abc')
True
>>> upper_lower('abcXYZ')
False
>>> upper_lower('XYZ')
True
"""

Regex is by far the most efficient way of doing this.

But if you'd like some pythonic flavor in your code, you can try this:

'abc'.isupper()
'ABC'.isupper()
'abcABC'.isupper()

upper_lower = lambda s: s.isupper() or s.islower()

Use re.match

if re.match(r'(?:[A-Z]+|[a-z]+)$', s):
    print("True")
else:
    print("Nah")

We don't need to add start of the line anchor since re.match tries to match from the beginning of the string.

So it enters in to the if block only if the input string contains only lowercase letters or only uppercase letters.

You can use the following regex:

if re.search('^([a-z]+|[A-Z]+)$', s):
    # all upper or lower case

Explanation: ^ matches the beginning of the string, [az] and [AZ] are trivial matches, + matches one or more. | is the "OR" regex, finally $ matches the end of the string.

Or, you can use all and check:

all(c.islower() for c in s)
# same thing for isupper()

You could collect all alphabetic characters and then check if all or upper or all are lower

a=[c for c in s if s.isalpha()]
if a:
    if "".join(a).isupper() or "".join(a).islower():
    print "yes"   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM