Python 如何检查一个字符串是否只包含大写字母
字符串是由字符组成的集合,可以表示一个单词或整个语句。在Python中使用字符串非常简单,因为它们不需要显式声明,并且可以带有或不带有修饰符定义。Python具有各种内置的函数和方法来操作和访问字符串。因为Python中的一切都是对象,所以字符串是String类的一个对象,具有几个方法。
在本文中,我们将了解如何在Python中检查一个字符串是否只包含大写字母。
使用isupper()函数
验证大写字母的一种方法是使用字符串库的isupper()函数。如果当前字符串中的每个字符都是大写字母,这个函数将返回 True ; 否则,它将返回 False 。
示例1
在下面给出的示例中,我们取两个字符串str1和str2,并检查它们是否包含除小写字母以外的任何字符。我们使用isupper()函数进行检查。
str1 = 'ABCDEF'
str2 = 'Abcdef'
print("Checking whether",str1,"is upper case")
print(str1.isupper())
print("Checking whether",str2,"is upper case")
print(str2.isupper())
输出
上述程序的输出是,
('Checking whether', 'ABCDEF', 'is upper case')
True
('Checking whether', 'Abcdef', 'is upper case')
False
示例2
以下是使用isupper()函数的另一个示例。在下面给出的程序中,我们正在检查如果大写单词之间有空格会发生什么情况。
str1 = 'WELCOME TO TUTORIALSPOINT'
print("Checking whether",str1,"is upper case")
print(str1.isupper())
输出
以上程序的输出为:
('Checking whether', 'WELCOME TO TUTORIALSPOINT', 'is upper case')
True
使用正则表达式
我们还可以使用正则表达式来确定给定的字符串是否包含小写字母。
为此,导入re库并安装(如果尚未安装)。在导入re库后,我们将使用正则表达式“[A Z]+$”。如果字符串包含除大写字母以外的任何字符,则会返回 False ;否则, True 将被返回。
示例
在下面的程序中,我们使用正则表达式‘[A Z]+$’来检查给定的字符串是否为大写。
import re
str1 = 'ABCDEF'
str2 = 'Abcdef'
print("Checking whether",str1,"is upper case")
print(bool(re.match('[A Z]+', str1)))
print("Checking whether",str2,"is uppercase")
print(bool(re.match('[A Z]+', str2)))
输出
以上程序的输出如下,
('Checking whether', 'ABCDEF', 'is upper case')
False
('Checking whether', 'Abcdef', 'is uppercase')
False
使用ASCII值
我们可以遍历字符串的每个字符,并根据ASCII值进行验证。我们知道大写字母的ASCII值介于65和90之间。如果每个ASCII值大于64且小于91,则返回True;否则返回False。
示例
在下面的示例中,我们编写一个checkupper()函数,并比较该字符串中每个字符的ASCII值。
def checkupper(str1):
n = len(str1)
count = 0
for i in str1:
if(64<ord(i) <91):
count += 1
if count == n:
return True
return False
str1 = 'ABCDEF'
str2 = 'Abcdef'
print("Checking whether",str1,"is upper case")
print(checkupper(str1))
print("Checking whether",str2,"is upper case")
print(checkupper(str2))
输出
上述程序的输出为,
('Checking whether', 'ABCDEF', 'is upper case')
True
('Checking whether', 'Abcdef', 'is upper case')
None