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