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


问题……

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

startswith() 方法

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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

示例

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('.')
# Let us first check if there are files
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

# list with choices
patters = ['.csv','.txt']

# get the file names
filenames = os.listdir('.')

# Let us first check if there are files
any(name.endswith(patters) for name in filenames)

输出

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
8
9 # Let us first check if there are files
---> 10 any(name.endswith(patters) for name in filenames)

in (.0)
8
9 # Let us first check if there are files
---> 10 any(name.endswith(patters) for name in filenames)

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

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

示例

# Let us first check if there are files
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>

更新于:2020年11月10日

838 次查看

开启您的职业生涯

完成课程获得认证

开始学习
广告