Skip to main content
 首页 » 编程设计

python之为什么 'Extended Iterable Unpacking' 不适用于空字符串

2025年05月04日33tuyile006

为什么是

>>> a, *b = ''  

不可能,当

>>> a, *b = ' ' 
>>> a, b 
(' ', [])  # b == empty list here anyway. 

和

>>> type('') 
<class 'str'> 

我的意思是,为什么不呢

>>> a, *b = '' 
>>> a, b  # a could == '' 
('', []) 

请您参考如下方法:

因为指定了一个强制变量。

右侧应该至少有一项(一个字符为字符串)。


根据 PEP-3131 :

A tuple (or list) on the left side of a simple assignment (unpacking is not defined for augmented assignment) may contain at most one expression prepended with a single asterisk (which is henceforth called a "starred" expression, while the other expressions in the list are called "mandatory"). This designates a subexpression that will be assigned a list of all items from the iterable being unpacked that are not assigned to any of the mandatory expressions, or an empty list if there are no such items.