Hatshepsut
Hatshepsut

Reputation: 6652

Extended tuple unpacking with unknown string format

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

Answers (4)

Artyer
Artyer

Reputation: 40826

There are two pitfalls here:

  • Dealing with multiple seperators
  • Not searching the string twice (i.e. splitting once)

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

Ajax1234
Ajax1234

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

randomir
randomir

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

Hatshepsut
Hatshepsut

Reputation: 6652

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

Upvotes: 4

Related Questions