如何在 Python 中检查字符串或字符串的子字符串是否以后缀结尾?
在 Python 中检查字符串或字符串的子字符串是否以某个后缀结尾,有多种方法可以实现。以下是一些示例
使用 endswith() 方法
endswith() 方法检查字符串是否以指定的后缀结尾,并返回布尔值。要检查字符串的子字符串是否以后缀结尾,可以使用字符串切片获取子字符串,然后对其应用 endswith()。
示例
string = "hello world"
suffix = "world"
if string.endswith(suffix):
print("String ends with suffix")
输出
String ends with suffix
使用 re 模块
re 模块为 Python 提供了正则表达式支持。可以使用正则表达式匹配字符串末尾的模式。以下是一个示例
示例
import re
string = "hello world"
suffix = "world"
pattern = re.compile(suffix + "$")
if pattern.search(string):
print("String ends with suffix")
输出
String ends with suffix
使用字符串切片
您还可以使用字符串切片来检查字符串或字符串的子字符串是否以后缀结尾。
示例
string = "hello world"
suffix = "world"
if string[-len(suffix):] == suffix:
print("String ends with suffix")
输出
String ends with suffix
要检查 Python 中的字符串或字符串的子字符串是否以特定后缀结尾,可以使用 str.endswith() 方法。如果字符串或子字符串以指定的后缀结尾,则此方法返回 True,否则返回 False。
示例
在此示例中,我们定义一个字符串 my_string 并检查它是否以指定的后缀“aboard!”结尾。由于它确实以该后缀结尾,因此程序打印“字符串以'aboard!'结尾”。
# Define a string
my_string = "Welcome, aboard!"
# Check if the string ends with "world!"
if my_string.endswith("aboard!"):
print("The string ends with 'aboard!'")
else:
print("The string does not end with 'aboard!'")
输出
The string ends with 'aboard!'
示例
在此示例中,我们定义了一个后缀列表和一个字符串 my_string。然后,我们使用带 any() 函数的生成器表达式来检查 my_string 是否以 suffixes 中的任何后缀结尾。由于 my_string 以后缀“.jpg”结尾,该后缀是列表中的一个后缀,因此程序打印“字符串以列表中的一个后缀结尾”。
# Define a list of suffixes
suffixes = [".jpg", ".png", ".gif"]
# Define a string
my_string = "picture.jpg"
# Check if the string ends with any of the suffixes
if any(my_string.endswith(suffix) for suffix in suffixes):
print("The string ends with one of the suffixes in the list")
else:
print("The string does not end with any of the suffixes in the list")
输出
The string ends with one of the suffixes in the list
示例
在此示例中,我们检查字符串 my_string 是否以指定的后缀“world”结尾。但是,由于 my_string 实际上以“world!”结尾,因此程序打印“字符串不以'world'结尾”。
# Define a string
my_string = "Hello, world!"
# Check if the string ends with "world"
if my_string.endswith("world"):
print("The string ends with 'world'")
else:
print("The string does not end with 'world'")
输出
The string does not end with 'world'
示例
在此示例中,我们检查字符串 my_string 是否以 suffixes 列表中的任何后缀结尾。但是,由于 my_string 以“.txt”结尾,该后缀不是列表中的一个后缀,因此程序打印“字符串不以列表中的任何后缀结尾”。
# Define a list of suffixes
suffixes = [".jpg", ".png", ".gif"]
# Define a string
my_string = "document.txt"
# Check if the string ends with any of the suffixes
if any(my_string.endswith(suffix) for suffix in suffixes):
print("The string ends with one of the suffixes in the list")
else:
print("The string does not end with any of the suffixes in the list")
输出
The string does not end with any of the suffixes in the list
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP