more questions...(strings)

Alex Martelli aleax at
Sun Feb 23 21:28:38 CET 2003

p.s wrote:

> Hi again,
> I've gotten some practice reading strings from files, and using raw_input,
> and now I'm looking into splitting strings.
> I know how to get something like "hello at there", split by doing
> str.split("@"), and I get a list of ["hello", "there"].
> However, I'm trying to get two lists, the first with the string before the
> "@", and the second list with the remainder of the string.
> So if i read from a file with:
> one at two
> white at black
> left at right
> I'd end up with this:
> list_one = ["one", "white", "left"]
> list_two = ["two", "black", "right"]
> thanks for reading.
> -p-

what about:

names_and_addresses = [ line[:-1].split('@') for line in thefile ]

list_one = [ name for name, address in names_and_addresses ]
list_two = [ address for name, address in names_and_addresses ]

this doesn't exactly respond to your "two lists" question as
posed in your text, but does seem to produce the result you want.

If you prefer to use explicit loops rather than list comprehensions:

list_one = []
list_two = []
for line in thefile:
    name, address = line[:-1].split('@')

is basically equivalent.


More information about the Python-list mailing list