如何在Python中检查字符串是否只包含大写字母?
字符串是一个包含字符的集合,可以表示一个单词或整个语句。在Python中,字符串使用简单,因为不需要明确声明,并且可以带或不带指定符定义。Python有各种内置的函数和方法来操作和访问字符串。因为Python中的所有东西都是对象,所以字符串是一个具有多个方法的String类的对象。
在本文中,我们将了解如何检查Python中的字符串是否只包含大写字母。
使用isupper()函数
验证大写字母的一种方法是使用字符串库的isupper()函数。如果当前字符串中的每个字符都是大写字母,则此函数返回 **True ** ; 否则,它返回 **False ** 。
示例1
在下面给出的示例中,我们使用isupper()函数获取2个字符串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库。导入re库后,我们将使用正则表达式 “[A Z]+$”。如果字符串包含除大写字母之外的任何字符,则会返回 **False ** ; 否则 **True ** 。
示例
在下面给出的程序中,我们使用正则表达式‘ [AZ]+ $’来检查给定字符串是否为大写。
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
极客教程