python - 安全解包空元组数组
问题描述
行import re; print(re.findall("(.*) (.*)", "john smith"))
输出[("john", "smith")]
,可以像[(first_name, last_name)] = re.findall(...)
. 但是,在不匹配(findall
返回[]
)的情况下,此拆包会抛出ValueError: not enough values to unpack (expected 1, got 0)
.
什么是安全解包这个元组数组的正确方法,它可以在匹配([("john", "smith")]
)和非匹配([]
)场景中工作?
解决方案
通用的答案是在你跳跃之前先看看:
if result:
[(first_name, last_name)] = result
或请求原谅:
try:
[(first_name, last_name)] = result
except ValueError:
pass
但是您实际上通过使用re.findall()
来查找单个结果使事情变得过于复杂。使用re.seach()
并提取您的匹配组:
match = re.search("(.*) (.*)", value)
if match:
firstname, lastname = match.groups()
或者
try:
firstname, lastname = re.search("(.*) (.*)", value).groups()
except AttributeError:
# An attribute error is raised when `re.search()` returned None
pass
推荐阅读
- java - 如何仅获取整数对象,仅字符串对象,甚至仅整数对象......?
- python - 多个字符串列上的熊猫聚合
- python - 用拉格朗日插值求多项式的常数项
- excel - 有没有办法根据特定单元格的值更改 VBA 代码?
- r - 将带有 % 的百分比列转换为 R 中的数字
- python - 如何在 C++ 中正确实现 python 迭代器?
- typescript - 扩展接口时的 Typescript 通用约束 - '?' 预期的
- javascript - Javascript - 引用函数本身的参数
- flutter - 在每个屏幕中保持底部导航栏颤动
- android - 即使应用程序关闭并在后台获取位置,也每天发送通知