Python 如何测试一个字符串的首字母是否为大写
字符串是由字符组成的集合,可以表示一个单词或整个句子。与Java不同,Python不需要显式声明字符串,我们可以直接将字符串值赋给一个文字。
在Python中,字符串由字符串类表示,该类提供了几个函数和方法,可以对字符串执行各种操作。
在本文中,我们将找出如何使用Python测试一个字符串的首字母是否为大写。
使用isupper()方法
实现这个目标的一种方法是使用内置的字符串方法 isupper() 。我们应该使用索引访问字符串的第一个字母,然后将该字符传递给 isupper() 方法,该方法如果给定的字符是大写,返回True,否则返回False。
示例1
在下面的示例中,我们输入一个字符串,并使用 isupper() 方法检查第一个字母是否为大写。
str1 = "Welcome to Tutorialspoint"
print("The given string is")
print(str1)
print("Checking if the first character is Capital or not")
if (str1[0].isupper()):
print("The first letter is a capital letter")
else:
print("The first letter is not a capital letter")
输出
上面示例的输出结果如下:
The given string is
Welcome to Tutorialspoint
Checking if the first character is Capital or not
The first letter is a capital letter
示例2
在下面给出的示例中,我们采用与上面相同的程序,但我们采用不同的输入并进行检查。
str1 = "welcome to Tutorialspoint"
print("The given string is")
print(str1)
print("Checking if the first character is Capital or not")
if (str1[0].isupper()):
print("The first letter is a capital letter")
else:
print("The first letter is not a capital letter")
输出
以上示例的输出结果为:
The given string is
welcome to Tutorialspoint
Checking if the first character is Capital or not
The first letter is not a capital letter
使用正则表达式
你可以使用Python的正则表达式来测试一个字符串是否以大写字母开头。要使用 re 库,首先导入并安装它(如果尚未安装)。
在导入re库后,我们将使用指定的正则表达式“substring”。使用 re.search() 函数检查文本是否以大写字母开头。
示例1
在下面给出的示例中,我们接受一个字符串作为输入,并使用正则表达式检查字符串的第一个字母是否为大写字母。
import re
str1 = "Welcome to Tutorialspoint"
print("The given string is")
print(str1)
print("Checking if the first character is Capital or not")
if re.search("^[A-Z]", str1):
print("The first letter is a capital letter")
else:
print("The first letter is not a capital letter")
输出
上述示例的输出如下:
The given string is
Welcome to Tutorialspoint
Checking if the first character is Capital or not
The first letter is a capital letter
示例2
在下面的示例中,我们将采用与上面相同的程序,但是我们将采用不同的输入并进行检查。
import re
str1 = "welcome to Tutorialspoint"
print("The given string is")
print(str1)
print("Checking if the first character is Capital or not")
if re.search("^[A-Z]", str1):
print("The first letter is a capital letter")
else:
print("The first letter is not a capital letter")
输出
上述示例的输出如下:
The given string is
welcome to Tutorialspoint
Checking if the first character is Capital or not
The first letter is not a capital letter