2017-08-06 49 views
3

我有一个字符串,它可能会或可能不会有一个|分隔符将其分成两个单独的部分。使用未知字符串格式解包扩展元组

有没有办法做扩展的元组拆包这样

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

,并有second_part == 'second part'而非['second part']?如果没有分隔符,second_part应该是''

+0

如果什么也没有这样的元素。那么'second_part'应该是什么? –

+0

@WillemVanOnsem''''见下面的答案 – Hatshepsut

+0

'b == second part'从哪里来?而'['第二部分']'? –

回答

4
first_part, _, second_part = 'might have | second part'.partition(' | ') 
2

你可以做这样的:

>>> 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') 
0

你可以试试这个:

s = 'might have | second part' 

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

a, *b = new_val 
0

有两个缺陷在这里:

  • 有多个分隔符
  • 没有搜索字符串处理的两倍(即分裂一次)

所以,如果你只是想拆就第一个分隔符(使用string.rsplit()最后分隔符):

def optional_split(string, sep, amount=2, default=''): 
    # Split at most amount - 1 times to get amount parts 
    parts = string.split(sep, amount - 1) 
    # Extend the list to the required length 
    parts.extend([default] * (amount - len(parts))) 
    return parts 
first_part, second_part = optional_split('might have | second part', ' | ', 2)