[英]Searching for a specific string connected to an attribute of an attribute of a list?
[英]searching specific string in list
如何在列表中搜索以特定字符串開頭的每個字符串,例如:
path = (r"C:\Users\Example\Desktop")
desktop = os.listdir(path)
print(desktop)
#['faf.docx', 'faf.txt', 'faad.txt', 'gas.docx']
所以我的問題是:我如何過濾每個以“fa”開頭的文件?
對於這種特定情況,涉及一個目錄中的文件名,您可以使用通配符:
import glob
import os
path = (r"C:\Users\Example\Desktop")
pattern = os.path.join(path, 'fa*')
files = glob.glob(pattern)
此代碼過濾掉所有以“fa”開頭的項目並將它們存儲在單獨的列表中
filtered = [item for item in path if item.startswith("fa")]
所有字符串都有一個.startswith()
方法!
results = []
for value in os.listdir(path):
if value.startswith("fa"):
results.append(value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.