如何在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

更新于:2022年10月19日

8K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.