Reputation: 6652
I have a string that may or may not have a |
separator breaking it into two separate parts.
Is there a way to do extended tuple unpacking like this
first_part, *second_part = 'might have | second part'.split(' | ')
and have second_part == 'second part'
rather than ['second part']
? If there is no separator, second_part
should be ''
.
Upvotes: 3
Views: 125
Reputation: 40826
There are two pitfalls here:
So, if you only want to split on the first seperators (Use string.rsplit()
for the last seperators):
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)
Upvotes: 0
Reputation: 71451
You can try this:
s = 'might have | second part'
new_val = s.split("|") if "|" in s else [s, '']
a, *b = new_val
Upvotes: 0
Reputation: 18697
You could do it like this:
>>> a, b = ('might have | second part'.split(' | ') + [''])[:2]
>>> a, b
('might have', 'second part')
>>> a, b = ('might have'.split(' | ') + [''])[:2]
>>> a, b
('might have', '')
The nice thing about this approach is that's it's easily generalized to n-tuple (while partition
will only split in part before separator, separator, and the part after):
>>> 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')
Upvotes: 2
Reputation: 6652
first_part, _, second_part = 'might have | second part'.partition(' | ')
Upvotes: 4