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

Gus Tabares gustabares at verizon.net
Tue Mar 23 22:53:04 EST 2004


There are multiple ways of doing this and they all vary depending on the
data. For instance, let's use the list you've provided us:

['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']


You have 27 characters that you don't care about, which is the date and
time info. Then you have 5 (or more) characters that you DO want. OK, so
let's try something like this:

>>> list = ['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']
>>> userlist = []
>>> for item in list:
	userlist.append(item[27:-2])
>>> print userlist
['user1', 'user2', 'user2', 'user3', 'user4']

This, of course, only works if you ALWAYS have those 27 characters in
front of the username you want and you always have a space followed by a
newline after the username.

You could also split each string in the list by whitespace and grab the
second-to-last item in the new list. But again, this is depends on the
format of your data.

HTH,
/Gus Tabares


-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of John Matthews
Sent: Tuesday, March 23, 2004 9:35 PM
To: tutor at python.org
Subject: [Tutor] How do I slice up a list of strings?

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']

How do I do that?

Thanks!
-- 
John Matthews
http://8ftarch.org

REGIME CHANGE 2004


_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list