String to List Question

Rhodri James rhodri at wildebst.demon.co.uk
Fri Jul 3 00:38:49 CEST 2009


On Thu, 02 Jul 2009 23:05:46 +0100, Hanna Michelsen <hannarosie at gmail.com>  
wrote:

> Hi,
>
> I am brand new to python and I love it, but I've been having some trouble
> with a file parser that I've been working on. It contains lines that  
> start
> with a name and then continue with names, nicknames and phone numbers of
> people associated with that name. I need to create a list of the names of
> people associated with each singular person (the first name in each  
> line).
> Each name/phone number is separated by a tab but if someone doesn't have  
> a
> nickname there are two tabs between their name and number.
>
> I've been trying to figure out how to test for two tabs, skip over these
> people and move onto the next name but I just can't figure out how that  
> will
> work in python.

You might find the csv module in the standard library does a lot of the
hard work for you: http://docs.python.org/library/csv.html

You can define yourself a reader that splits the input on tabs, and
then see how long the rows it returns are.  Something like this
(untested):

import csv

for row in csv.reader(open("phone_numbers.txt", "rb"), delimiter='\t'):
     if len(row) > 1:
         # Do your stuff

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list