如何在Python中检查一个字符串是否只包含小写字母?

如何在Python中检查一个字符串是否只包含小写字母?

一个字符串是一组字母,可以用来表示单个单词或全部陈述。由于Python不需要显式地声明,因此对于Python来说,字符串很容易使用,也可以带或不带限定符定义。

为了操作和访问字符串,Python包括几个内置函数和方法。在Python中,字符串是String类的对象。

在本文中,我们将讨论如何在Python中检查一个字符串是否只包含小写字母。有多种方法可用。

使用islower()方法

检查字符串中小写字母的一种方法是使用字符串库的islower()方法。该方法对于当前字符串中的每个字符都返回True,如果有一个不是小写字符,则返回False。

示例1

在下面的示例中,我们正在使用2个字符串str1和str2,并检查它们是否包含除小写字母以外的任何字符。我们正在使用islower()函数进行检查。

str1 = 'abcdef'
str2 = 'Abcdef'

print("Checking whether", str1, "is lower case")
print(str1.islower())

print("Checking whether", str2, "is lower case")
print(str2.islower())

输出

以上程序的输出结果是,

('Checking whether', 'abcdef', 'is lower case')
True
('Checking whether', 'Abcdef', 'is lower case')
False

示例2

以下是另一个示例,使用islower()方法。

在下面的程序中,我们检查如果小写字符之间有空格会发生什么。

str1 = 'welcome to tutorialspoint'

print("Checking whether", str1, "is lower case")
print(str1.islower())

输出

以上程序的输出结果是,

('Checking whether', 'welcome to tutorialspoint', 'is lower case')
True

使用正则表达式

我们还可以使用正则表达式来确定给定的字符串是否包含小写字母。为此,导入并安装re库(如果尚未安装)。

导入re库后,我们将使用正则表达式“[a z]+$”。如果字符串包含除小写字符以外的任何字符,则返回False;否则,将返回True。

示例

在下面的程序中,我们使用正则表达式‘[a z]+$’来检查给定字符串是否为小写。

import re

str1 = 'abcdef'
str2 = 'Abcdef'

print("检查",str1,"是否为小写")
print(bool(re.match('[a z]+', str1)))

print("检查",str2,"是否为小写")
print(bool(re.match('[a z]+', str2)))

输出

上述程序的输出结果为,

('检查', 'abcdef', '是否为小写')
False
('检查', 'Abcdef', '是否为小写')
False

使用ASCII值

我们可以逐个字符遍历字符串并根据ASCII值进行验证。我们知道小写字母的ASCII值从97开始,所以我们必须检查每个ASCII值是否大于97。如果每个ASCII值大于97,则返回True,否则返回False。

例子

在以下给出的例子中,我们编写一个checkLower()函数,并对该字符串中的每个字符进行ASCII值比较。 如果每个字符的ASCII值大于96且小于122,则返回 **True ** 否则返回 **False ** 。

def checkLower(str1):
   n = len(str1)
   count = 0
   for i in str1:
      if(122>= ord(i) >= 97):
         count += 1

   if count == n:
      return True
      return False

str1 = 'abcdef'
str2 = 'Abcdef'

print("检查",str1,"是否为小写")
print(checkLower(str1))

print("检查",str2,"是否为小写")
print(checkLower(str2))

输出

上述程序的输出结果为,

('检查', 'abcdef', '是否为小写')
True
('检查', 'Abcdef', '是否为小写')
None

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程