What's correct Python syntax?

Roy Smith roy at panix.com
Tue Jan 14 08:34:31 EST 2014


In article <mailman.5437.1389689219.18130.python-list at python.org>,
 Igor Korot <ikorot01 at gmail.com> wrote:

> Hi, ALL,
> I'm trying to process a file which has following lines:
> 
> 192.168.1.6 > 192.168.1.7: ICMP echo request, id 100, seq 200, length 30
> 
> (this is the text file out of tcpdump)
> 
> Now I can esily split the line twice: once by ':' symbol to separate
> address and the protocol information and the second time by ',' to get
> information about the protocol.
> However, I don't need all the protocol info. All I'm interested in is
> the last field, which is length.

One possibility would be to forget about all the punctuation and just 
use "length " (note the trailing space) as the split delimiter:

>>> line = '192.168.1.6 > 192.168.1.7: ICMP echo request, id 100, seq 
200, length 30'
>>> line.split('length ')
'30'

this will only work if you're sure that "length " can never appear 
anywhere else in the line.  Another, perhaps more idiomatic, way would 
be:

>>> _, length = line.split('length ')
>>> print length
30

What's happening here is split() is returning a list of two items, which 
you then unpack into two variables, "_" and "length".  It's common to 
unpack unwanted fields into "_", as a hint (to the reader) that it's 
unused.



More information about the Python-list mailing list