如何在Python中匹配字串的開頭或結尾文字?


問題……

假設您需要檢查字串的開頭或結尾是否存在特定文字模式。常見的模式可能是檔名副檔名,但也可能是任何內容。我將向您展示幾種執行此操作的方法。

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('.')
# 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 次檢視

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.