![](/img/trans.png)
[英]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.