[英]searching specific string in list
How to search for every string in a list that starts with a specific string like:如何在列表中搜索以特定字符串开头的每个字符串,例如:
path = (r"C:\Users\Example\Desktop")
desktop = os.listdir(path)
print(desktop)
#['faf.docx', 'faf.txt', 'faad.txt', 'gas.docx']
So my question is: how do i filter from every file that starts with "fa"?所以我的问题是:我如何过滤每个以“fa”开头的文件?
For this specific cases, involving filenames in one directory, you can use globbing:对于这种特定情况,涉及一个目录中的文件名,您可以使用通配符:
import glob
import os
path = (r"C:\Users\Example\Desktop")
pattern = os.path.join(path, 'fa*')
files = glob.glob(pattern)
This code filters all items out that start with "fa" and stores them in a separate list此代码过滤掉所有以“fa”开头的项目并将它们存储在单独的列表中
filtered = [item for item in path if item.startswith("fa")]
All strings have a .startswith()
method!所有字符串都有一个.startswith()
方法!
results = []
for value in os.listdir(path):
if value.startswith("fa"):
results.append(value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.