如何在 Python 中检查字符串或字符串的子字符串是否以后缀结尾?
要在 Python 中检查字符串或字符串的子字符串是否以后缀结尾,有几种方法可以实现此目的。以下是一些示例:
使用 endswith() 方法
endswith() 方法检查字符串是否以指定的后缀结尾并返回布尔值。要检查字符串的子字符串是否以后缀结尾,可以使用字符串切片来获取子字符串,然后对其应用 endswith()。
示例
string = "hello world" suffix = "world" if string.endswith(suffix): print("字符串以后缀结尾")
输出
字符串以后缀结尾
使用 re 模块
re 模块为 Python 中的正则表达式提供支持。您可以使用正则表达式来匹配字符串末尾的模式。以下是示例:
示例
import re string = "hello world" suffix = "world" pattern = re.compile(suffix + "$") if pattern.search(string): print("字符串以后缀结尾")
输出
字符串以后缀结尾
使用字符串切片
您还可以使用字符串切片来检查字符串或字符串的子字符串是否以后缀结尾。
示例
string = "hello world" suffix = "world" if string[-len(suffix):] == suffix: print("字符串以后缀结尾")
输出
字符串以后缀结尾
要在 Python 中检查字符串或字符串的子字符串是否以特定后缀结尾,可以使用 str.endswith() 方法。如果字符串或子字符串以指定的后缀结尾,则此方法返回 True,否则返回 False。
示例
在此示例中,我们定义一个字符串 my_string 并检查它是否以指定的后缀"aboard!"结尾。由于它确实以此后缀结尾,因此程序会打印"字符串以 'aboard!' 结尾"。
# 定义一个字符串 my_string = "Welcome, aboard!" # 检查字符串是否以"world!"结尾 if my_string.endswith("aboard!"): print("字符串以 'aboard!' 结尾") else: print("字符串不以 'aboard!' 结尾")
输出
字符串以 'aboard!' 结尾
示例
在此示例中,我们定义了一个后缀列表和一个字符串 my_string。然后,我们使用带有 any() 函数的生成器表达式来检查 my_string 是否以后缀中的任何后缀结尾。由于 my_string 以后缀".jpg"结尾,而后缀是列表中的后缀之一,因此程序会打印"字符串以列表中的后缀之一结尾"。
# 定义后缀列表 suffixes = [".jpg", ".png", ".gif"] # 定义字符串 my_string = "picture.jpg" # 检查字符串是否以任何后缀结尾 if any(my_string.endswith(suffix) for suffix in suffixes): print("字符串以列表中的后缀之一结尾") else: print("字符串不以列表中的任何后缀结尾")
输出
字符串以以下后缀之一结尾列表中的后缀
示例
在此示例中,我们检查字符串 my_string 是否以指定的后缀"world"结尾。但是,由于 my_string 实际上以"world!"结尾,因此程序会打印"字符串不以 'world' 结尾"。
# 定义字符串 my_string = "Hello, world!" # 检查字符串是否以"world"结尾 if my_string.endswith("world"): print("字符串以 'world' 结尾") else: print("字符串不以 'world' 结尾")
输出
字符串不以 'world' 结尾
示例
在此示例中,我们检查字符串 my_string 是否以后缀列表中的任何后缀结尾。但是,由于 my_string 以".txt"结尾,而 .txt 不是列表中的后缀之一,因此程序会打印"字符串不以列表中的任何后缀结尾"。
# 定义后缀列表 suffixes = [".jpg", ".png", ".gif"] # 定义字符串 my_string = "document.txt" # 检查字符串是否以任何后缀结尾 if any(my_string.endswith(suffix) for suffix in suffixes): print("字符串以列表中的后缀之一结尾") else: print("字符串不以列表中的任何后缀结尾")
输出
字符串不以任何后缀结尾列表中的后缀