python判断小写字母

2023-07-30 python 判断 字母

方法一:使用islower()

Python中内置了islower()方法,可以直接判断一个字符是否为小写字母。islower()方法返回True或False。代码如下:

# 单个字符判断
char1 = 'a'
char2 = 'A'
print(char1.islower())    # True
print(char2.islower())    # False

# 字符串中每个字符都满足条件才返回True
str1 = 'pidancode.com'
str2 = '皮蛋编程'
print(str1.islower())     # True
print(str2.islower())     # False

方法二:使用ASCII码判断

小写字母的ASCII码范围是97~122,使用ord()获取字符对应的ASCII码,再进行判断。代码如下:

# 单个字符判断
char1 = 'a'
char2 = 'A'
print(ord(char1) >= 97 and ord(char1) <= 122)    # True
print(ord(char2) >= 97 and ord(char2) <= 122)    # False

# 字符串中每个字符都满足条件才返回True
str1 = 'pidancode.com'
str2 = '皮蛋编程'
print(all(ord(c) >= 97 and ord(c) <= 122 for c in str1))    # True
print(all(ord(c) >= 97 and ord(c) <= 122 for c in str2))    # False

以上两种方法均可以用来判断小写字母,但islower()方法更为简便易用。

相关文章