首页 > 解决方案 > 安全解包空元组数组

问题描述

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")])和非匹配([])场景中工作?

标签: pythonpython-3.xtuplesiterable-unpacking

解决方案


通用的答案是在你跳跃之前先看看:

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

推荐阅读