如何在 Python 中匹配字符串开头或结尾的文本?

pythonserver side programmingprogramming更新于 2026/2/15 14:36:17

问题..

假设您需要检查字符串的开头或结尾是否为特定的文本模式。常见模式可能是文件扩展名,但也可以是任何内容。我将向您展示几种如何执行此操作的方法。

Startswith() 方法

检查字符串开头的一种简单方法是使用 startswith() 方法。

示例

text = "Is USA colder than Australia?"
print(f"output \n {text.startswith('Is')}")

输出

True

示例

filename = "Hello_world.txt"
print(f"output \n {filename.startswith('Hello')}")

输出

True

示例

site_url = 'https://www.something.com'
print(f"output \n {site_url.startswith('http:')}")

输出

False

示例

print(f"output \n {site_url.startswith('https:')}")

输出

True

endswith() 方法。

检查字符串结尾的一个简单方法是使用 endswith() 方法。

输出

text = "Is USA colder than Australia?"
print(f"output \n {text.endswith('?')}")

输出

True

示例

filename = "Hello_world.txt"
print(f"output \n {filename.endswith('.txt')}")

输出

True

现在,如果我们想使用上述方法检查多个选择,我们需要提供元组。一种常见用法是检查文件扩展名,假设我们需要验证目录中的".txt"和".csv"文件。

import os
filenames = os.listdir('.')
# 让我们首先检查是否有文件
print(f"output \n {any(name.endswith(('.csv',',txt')) for name in filenames)}")

输出

True

输出

[name for name in filenames if name.endswith(('.csv', '.txt')) ]

输出

['file1.csv',
'HRDataset.csv',
'Input.csv',
'input.txt',
'input_copy.txt',
'movies_data.csv',
'my_html_data_to_csv.csv',
'temporary_file1_for_zip.csv',
'temporary_file2_for_zip.csv',
'test.csv',
'test1.txt',
'test2.txt',
'tmdb_5000_movies.csv']

请记住,这些方法接受元组,如果您有一个要搜索的选择列表,那么我们需要将它们转换为元组。

import os

# 带有选择的列表
patters = ['.csv','.txt']

# 获取文件名
filenames = os.listdir('.')

# 让我们首先检查是否有文件
any(name.endswith(patters) for name in filenames)

输出

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
8
9 # 让我们先检查是否有文件
---> 10 any(name.endswith(pattern) for name in filenames)
in (.0)

8
9 # 让我们先检查是否有文件
---> 10 any(name.endswith(patters) for name in filenames)

TypeError: endswith first arg must be str or a tuple of str, not list

上述命令返回错误,因此我们需要将列表转换为元组。

示例

# 首先检查是否有文件
any(name.endswith(tuple(patters)) for name in filenames)

输出

True

同样,我们需要将列表转换为元组以获取文件名。

示例

[name for name in filenames if name.endswith(tuple(patters)) ]

输出

['file1.csv',
'HRDataset.csv',
'Input.csv',
'input.txt',
'input_copy.txt',
'movies_data.csv',
'my_html_data_to_csv.csv',
'temporary_file1_for_zip.csv',
'temporary_file2_for_zip.csv',
'test.csv',
'test1.txt',
'test2.txt',
'tmdb_5000_movies.csv']

最后,startswith() 和 endswith() 方法与其他操作(如常见的数据缩减)结合使用时效果很好。例如:

示例

if any(name.endswith(tuple(patters)) for name in filenames):
<perform the logic here>

相关文章


有用资源