Python – Unpacking Variables


So sometimes you will have input data and you will want it added to variables. I’m currently learning there are a lot of neat ways to do so.

specifically you can use an * to represent fields that you know will exist, but you might not know how many, but there is a pattern.

>>> line = 'nobody:*:-2:Unprivileged User:/var/empty:/usr/bin/false'
>>> uname, *fields, homedir, sh = line.split(':')
>>> uname
'nobody'
>>> homedir
'/var/empty'
>>> fields
['*', '-2', 'Unprivileged User']
>>>

Just an example I took from a book I am reading, and I just find it really clever. It is splitting the data using ‘:’ , with line.split(‘:’).

['nobody', '*', '-2', 'Unprivileged User', '/var/empty', '/usr/bin/false']

That is what line.split will do, you now have a list of 6 strings, you then have the variables equal that list, uname gets the first, *fields gets the rest except for the last two which goes into homedir and sh respectively since you specified them being last in order.

It’s almost magical.


Leave a Reply

Test Your email address will not be published. Required fields are marked *