Best way to delimit a list?

J. Clifford Dyer jcd at sdf.lonestar.org
Tue May 13 08:15:55 EDT 2008


On Tue, 2008-05-13 at 03:28 -0700, dannywebster at googlemail.com wrote:
> Hi - I have a list returned from popen/readlines, and am wondering how
> to go about iterating over each item which was returned (rather than
> currently having the whole lot returned).
> 
> so far:
> 
> >>> f=os.open("./get_hostnames").readlines
> 
> returns ['host1 host2 host3 ... hostN\n]'
> 
> i'd like to be in a position to iterate through these, grabbing each
> host.  I have played with transmuting to a str, and using split, and
> this works, but I get the subscript brackets from the list output as
> expected, as the list output is now a string literal, and this is not
> what I want - and I think it's a bit long-winded to do a search 'n
> replace on it - hence why I ask in the subject what's the best way.
> 
> >>> f=str(f)
> >>> f.split()
> ["['host1","host2", ... ,"hostN\n']"]
> 

Instead of casting to a string, each element of your list is already a
string, so use that instead:

f = open("get_hostnames")
hosts =[]

# gets each string one at a time.
for line in f:
    # get rid of the pesky \n at the end
    line = line.strip()
    # separate the hostnames into a list
    hosts += line.split(' ')

> Any help is highly appreciated
> 
> ta
> 
> dan.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list