如何在Python中检查字符串是否以XYZ开头?
字符串是由多个字符组成的集合,存储为单个值。与其他技术不同,Python中不需要显式声明字符串(实际上任何变量),只需要将字符串赋值给字面量,这使得Python字符串易于使用。
在Python中,字符串由名为String的类表示。此类提供多个函数和方法,可以使用它们对字符串执行各种操作。
在本文中,我们将了解如何在Python中检查字符串是否以XYZ开头。
使用startswith()方法
实现此目标的一种方法是使用内置的startswith()方法。Python中的String类包含一个名为startswith(string)的函数。此函数在字符串对象上执行,并接收您要搜索的前缀字符串。
此方法被赋予一个字符串,子字符串作为参数给出,如果字符串以子字符串开头,则返回True,否则返回False。
示例1
在下面的示例中,我们以字符串和子字符串作为输入,并使用startswith()方法检查字符串是否以子字符串开头。
str1 = "Welcome to Tutorialspoint" print("The given string is") print(str1) substr = "Wel" print("The given substring is") print(substr) print("Checking if the string is starting with the substring") print(str1.startswith(substr))
输出
上述示例的输出为:
The given string is Welcome to Tutorialspoint The given substring is Wel Checking if the string is starting with the substring True
示例2
在下面的示例中,我们使用与上述相同的程序,但输入不同,并检查字符串是否以子字符串开头。
str1 = "Welcome to Tutorialspoint" print("The given string is") print(str1) substr = "XYZ" print("The given substring is") print(substr) print("Checking if the string is starting with the substring") print(str1.startswith(substr))
输出
上述示例的输出为:
The given string is Welcome to Tutorialspoint The given substring is XYZ Checking if the string is starting with the substring False
使用正则表达式
第二种技术使用正则表达式。导入re库,如果尚未安装,请安装它以使用它。导入re库后,我们将使用正则表达式"^substring"。re.search()函数使用正则表达式检查文本是否以指定的子字符串开头。
示例1
在下面的示例中,我们以字符串和子字符串作为输入,并使用re.search方法检查字符串是否以子字符串开头。
import re str1 = "Welcome to Tutorialspoint" print("The given string is") print(str1) substr = "Wel" print("The given substring is") print(substr) print("Checking if the string is starting with the substring") print(bool(re.search("^Wel", str1)))
输出
上述示例的输出为:
The given string is Welcome to Tutorialspoint The given substring is Wel Checking if the string is starting with the substring True
示例2
在下面的示例中,我们使用与上述相同的程序,但输入不同,并检查字符串是否以子字符串开头。
import re str1 = "Welcome to Tutorialspoint" print("The given string is") print(str1) substr = "XYZ" print("The given substring is") print(substr) print("Checking if the string is starting with the substring") print(bool(re.search("^XYZ", str1)))
输出
上述示例的输出为:
The given string is Welcome to Tutorialspoint The given substring is XYZ Checking if the string is starting with the substring False
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP