You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python断言中如何忽略f-string指定片段,实现多值匹配?

在Python assert中用正则实现部分内容的多值匹配

当然可以用正则表达式实现这种需求,直接通过re.fullmatch()来验证目标字符串是否符合指定格式即可,具体写法如下:

示例代码

import re

# 原固定值断言
# assert results.to_dict()["comment"] == "Retrying in 3600 seconds (1/5)"

# 改为正则匹配,允许括号内第一个数字为1-5
assert re.fullmatch(r"Retrying in 3600 seconds \([1-5]/5\)", results.to_dict()["comment"]) is not None

正则表达式说明

  • \( 和 \):转义正则中的特殊字符(和),确保匹配字符串里的实际括号
  • [1-5]:匹配1到5之间的任意单个数字
  • 其余部分和原固定字符串完全一致,保证除了指定位置外的内容严格匹配

补充说明

如果需要更灵活的匹配(比如3600秒也可能是变量),可以调整正则中的对应部分,比如用\d+匹配任意数字:

assert re.fullmatch(r"Retrying in \d+ seconds \([1-5]/5\)", results.to_dict()["comment"]) is not None

内容的提问来源于stack exchange,提问作者lukos06

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:13:12