具有未知字符串形式的扩展元组解包

2024-04-26 04:42:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,可能有,也可能没有,有一个|分隔符,把它分成两个独立的部分。你知道吗

有没有办法像这样解包扩展元组

first_part, *second_part = 'might have | second part'.split(' | ') 

second_part == 'second part'而不是['second part']?如果没有分隔符,second_part应该是''。你知道吗


Tags: 字符串havefirstsplit元组secondmight分隔符
3条回答
first_part, _, second_part = 'might have | second part'.partition(' | ')

你可以试试这个:

s = 'might have | second part'

new_val = s.split("|") if "|" in s else [s, '']

a, *b = new_val

你可以这样做:

>>> a, b = ('might have | second part'.split(' | ') + [''])[:2]
>>> a, b
('might have', 'second part')
>>> a, b = ('might have'.split(' | ') + [''])[:2]
>>> a, b
('might have', '')

这种方法的优点在于,它很容易推广到n元组(而partition只会在分隔符、分隔符和后面的部分之前分割):

>>> a, b, c = ('1,2,3'.split(',') + list("000"))[:3]
>>> a, b, c
('1', '2', '3')
>>> a, b, c = ('1,2'.split(',') + list("000"))[:3]
>>> a, b, c
('1', '2', '0')
>>> a, b, c = ('1'.split(',') + list("000"))[:3]
>>> a, b, c
('1', '0', '0')

相关问题 更多 >