A common problem for (space) separated string parsing is that there are a number of fixed items followed by some amount of optional items. You want to extract parsed values to Python variables and initialize optional values with None if they are missing.
E.g. we have option format description string with 2 or 3 items value1 value2 [optional value]
s = "foo bar" # This is a valid example option string
s2 = "foo bar optional" # This is also, with one optional item
Usually we’d like to parse this so that non-existing options are set to None. Traditonally one does Python code like below:
# Try get extration and deletion
parts = s.split(" ")
value1 = parts[0]
value2 = parts[1]
if len(parts) >= 3:
optional_value = parts[2]
else:
optionanl_value = None
However, this looks little bit ugly, considering if there would always be just two options one could write:
value1, value2 = s.split(" ")
When the number of optional options grow, the boiler-plate code starts annoy greatly.
I have been thinking how to write a split() code to parse options with non-existing items to be set None. Below is my approach for a string with total of 4 options of which any number can be optional.
parts = s.split(" ", 4) # Will raise exception if too many options
parts += [None] * (4 - len(parts)) # Assume we can have max. 4 items. Fill in missing entries with None.
value1, value2, optional_value, optional_value2 = parts
Any ideas for something more elegant?
Get developers
Subscribe mFabrik blog in a reader
Follow me on Twitter

