Skip to main content
 首页 » 编程设计

python之如何检查字符串是否只包含大写或小写字母

2024年10月24日35Leo_wl

当且仅当 s 中至少有一个字母字符且 s 中的字母字符要么全部大写要么全部小写时返回 True。

def upper_lower(s): 
 
   """ (str) -> bool 
 
 
 
>>> upper_lower('abc') 
True 
>>> upper_lower('abcXYZ') 
False 
>>> upper_lower('XYZ') 
True 
""" 

请您参考如下方法:

使用re.match

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

我们不需要添加行 anchor 的开头,因为 re.match 尝试从字符串的开头开始匹配。

所以只有当输入字符串只包含小写字母或只包含大写字母时,它才会进入if block 。