I'm reading a file and unpacking each line like this:
for line in filter(fh):
a, b, c, d = line.split()
However, it's possible that line may have more or fewer columns than the variables I wish to unpack. In the case when there are fewer, I'd like to assign None
to the dangling variables, and in the case where there are more, I'd like to ignore them. What's the idiomatic way to do this? I'm using python 2.7.
Fix the length of the list, padding with None
.
def fixLength(lst, length):
return (lst + [None] * length)[:length]
In python 3 you can use this
a, b, c, d, *_unused_ = line.split() + [None]*4
Edit
For large strings I suggest to use maxsplit
-argument for split (this argument also works in py2.7):
a, b, c, d, *_unused_ = line.split(None, 4) + [None]*4
Why 5? Otherwise the 4th element would consist the whole residual of the line.
Edit2 It is 4… It stops after 4 splits, not 4 elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With