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

更新于: 2022-10-26

373 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.