扩展元组以未知字符串格式解压缩

时间:2017-08-06 23:16:22

标签: python iterable-unpacking

我有一个字符串,可能会或可能不会first_part, *second_part = 'might have | second part'.split(' | ') 分隔符分成两个独立的部分。

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

second_part == 'second part'

并且['second part']而不是second_part?如果没有分隔符,则''应为{{1}}。

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分: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')

答案 2 :(得分:0)

你可以试试这个:

s = 'might have | second part'

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

a, *b = new_val

答案 3 :(得分: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)