[英]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.当且仅当 s 中至少有一个字母字符且 s 中的字母字符全部大写或全部小写时,才返回 True。
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:但是如果你想在你的代码中加入一些 Python 风格,你可以试试这个:
'abc'.isupper()
'ABC'.isupper()
'abcABC'.isupper()
upper_lower = lambda s: s.isupper() or s.islower()
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.我们不需要添加行锚点的开头,因为re.match
尝试从字符串的开头进行匹配。
So it enters in to the if
block only if the input string contains only lowercase letters or only uppercase letters.因此,仅当输入字符串仅包含小写字母或仅包含大写字母时,它才会进入if
块。
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.说明: ^
匹配字符串的开头, [az]
和[AZ]
是普通匹配, +
匹配一个或多个。 |
is the "OR" regex, finally $
matches the end of the string.是“OR”正则表达式,最后$
匹配字符串的结尾。
Or, you can use all
and check:或者,您可以使用all
并检查:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.