[英]Extended tuple unpacking with unknown string format
我有一個字符串, 可能有也可能沒有 |
分離器將其分成兩個獨立的部分。
有沒有辦法像這樣做擴展元組解包
first_part, *second_part = 'might have | second part'.split(' | ')
並有second_part == 'second part'
而不是['second part']
? 如果沒有分隔符,則second_part
應為''
。
first_part, _, second_part = 'might have | second part'.partition(' | ')
你可以這樣做:
>>> 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')
你可以試試這個:
s = 'might have | second part'
new_val = s.split("|") if "|" in s else [s, '']
a, *b = new_val
這里有兩個陷阱:
所以,如果你只想拆分第一個分隔符(使用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.