2017-08-06 47 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)