Extended unpacking of a tuple with an unknown string format

I have a string that may or may not have a separator |

splitting it into two separate parts.

Is there a way to do the expanded tuple unpacking like this:

first_part, *second_part = 'might have | second part'.split(' | ') 

      

and second_part == 'second part'

instead of ['second part']

? If there is no separator, there second_part

should be ''

.

+3


source to share


4 answers


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

      



+4


source


You can 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 best part about this approach is that it easily generalizes to an n-tuple (while it partition

will only split before the split, delimiter, 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')

      

+2


source


You can try this:

s = 'might have | second part'

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

a, *b = new_val

      

0


source


There are two errors here:

  • Working with multiple delimiters
  • Don't search twice in a string (i.e. split once)

So if you only want to split the first separators (use string.rsplit()

for the last separators):

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)

      

0


source







All Articles