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