Can I set the default value when unpacking?
I have the following:
>>> myString = "has spaces"
>>> first, second = myString.split()
>>> myString = "doesNotHaveSpaces"
>>> first, second = myString.split()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
I would like to have seconda default Noneif the string has no space. I currently have the following, but I am wondering if this can be done on one line:
splitted = myString.split(maxsplit=1)
first = splitted[0]
second = splitted[1:] or None
May I suggest you use a different method, i.e. partitioninstead of split:
>>> myString = "has spaces"
>>> left, separator, right = myString.partition(' ')
>>> left
'has'
>>> myString = "doesNotHaveSpaces"
>>> left, separator, right = myString.partition(' ')
>>> left
'doesNotHaveSpaces'
If you are on python3, you have this option:
>>> myString = "doesNotHaveSpaces"
>>> first, *rest = myString.split()
>>> first
'doesNotHaveSpaces'
>>> rest
[]
A general solution would be chainyour iterable using repeatvalues None, and then use the isliceresult:
from itertools import chain, islice, repeat
none_repat = repeat(None)
example_iter = iter(range(1)) #or range(2) or range(0)
first, second = islice(chain(example_iter, none_repeat), 2)
None, , :
def fill_iter(it, size, fill_value=None):
return islice(chain(it, repeat(fill_value)), size)
, , str.partition.