Home:ALL Converter>How can I check if a string only contains uppercase or lowercase letters?

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

Ask Time:2015-07-02T15:20:38         Author:Scott Wang

Json Formatter

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
"""

Author:Scott Wang,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/31177983/how-can-i-check-if-a-string-only-contains-uppercase-or-lowercase-letters
Avinash Raj :

Use re.match\n\nif re.match(r'(?:[A-Z]+|[a-z]+)$', s):\n print(\"True\")\nelse:\n print(\"Nah\")\n\n\nWe don't need to add start of the line anchor since re.match tries to match from the beginning of the string.\n\nSo it enters in to the if block only if the input string contains only lowercase letters or only uppercase letters.",
2015-07-02T07:25:45
crsxl :

Regex is by far the most efficient way of doing this.\n\nBut if you'd like some pythonic flavor in your code, you can try this:\n\n'abc'.isupper()\n'ABC'.isupper()\n'abcABC'.isupper()\n\nupper_lower = lambda s: s.isupper() or s.islower()\n",
2015-07-02T07:22:53
Maroun :

You can use the following regex:\n\nif re.search('^([a-z]+|[A-Z]+)$', s):\n # all upper or lower case\n\n\nExplanation: ^ matches the beginning of the string, [a-z] and [A-Z] are trivial matches, + matches one or more. | is the \"OR\" regex, finally $ matches the end of the string.\n\nOr, you can use all and check:\n\nall(c.islower() for c in s)\n# same thing for isupper()\n",
2015-07-02T07:26:29
yy