[Tutor] How do I slice up a list of strings?

Karl Pflästerer sigurd at 12move.de
Wed Mar 24 12:49:45 EST 2004


On 24 Mar 2004, John Matthews <- jmatthew at columbus.rr.com wrote:

> I read in data from a log file that looks like this:

> ['Tue 03/23/2004 13:11:07.49 user1 \n', 'Tue 03/23/2004 13:45:07.34
> user2 \n', 'Tue 03/23/2004 13:46:13.53 user2 \n', 'Tue 03/23/2004
> 14:22:08.45 user3 \n', 'Tue 03/23/2004 15:17:58.38 user4 \n']

> I want to slice the stings so that the list becomes:

> ['user1', 'user2', 'user2', 'user3', 'user4']


What you want is the last word of each line. So if you read the log file
with:

log = file('foo.log')
users = [line.split()[-1] for line in log]
log.close()

What happens here is:
(a) the file gets opened
(b) a list gets build with a list comprehension
    o each line is read in the variable line
    o each line gets split on whitespace
    o from each splitted line the last item is saved as entry for the
      new build list
(c) the file is closed


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list