Breaking the barrier of a broken paradigm... part 1

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Mar 25 12:34:48 EDT 2008


En Tue, 25 Mar 2008 07:44:59 -0300, john s. <john.jython at gmail.com>  
escribió:

>> for line in open("/etc/passwd"):
>>     user, _pwd = line.split(":")
>            ^----- Ok this one here we are taking a string spliting it
> into to variables...
>            user gets one (the first) and _pwd gets to hold the
> "leftovers"?

No; if the line contains more than a single : that code will fail.
user, remainder = line.split(":", 1)

With Python 3.0 you could write:
user, _pwd, *other = line.split(":")
but limiting the number of splits is more efficient if you are not  
interested in the remaining list. A more interesting case is:
a, b, *other, c = line.split(":")
to obtain the first, second and last items.

-- 
Gabriel Genellina




More information about the Python-list mailing list