← 中文资源

简体中文版本

startswith 与 endswith 匹配前缀元组

startswith 和 endswith 接受元组参数:一次调用就能匹配多个前缀或后缀,按扩展名筛选文件列表时特别顺手。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

logs : ['app.log', 'error.log', 'notes.txt', 'debug.LOG']
match: ['app.log', 'access.log.1', 'debug.LOG']
json : ['data.json']

实现说明

演示用的数据放在这几个模块级绑定中:logs、log_files、rotated、json_only。

使用要点

  • 每一步打印都带着自己的标签:logs :、match:、json :。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 状态都挂在模块顶层:logs、log_files、rotated。

代码示例

logs = [
    "app.log",
    "error.log",
    "data.json",
    "notes.txt",
    "access.log.1",
    "debug.LOG",
    "report.pdf",
]

# tuple argument: 一次匹配多个后缀/前缀,不必手写 or 链
log_files = [name for name in logs if name.lower().endswith((".log", ".txt"))]
print("logs :", log_files)

rotated = [name for name in logs if name.startswith(("access", "debug", "app"))]
print("match:", rotated)

json_only = [name for name in logs if name.endswith(".json")]
print("json :", json_only)