list comprehension for splitting strings into pairs

Steven Bethard steven.bethard at gmail.com
Wed Oct 13 00:11:45 CEST 2004


Here's what I'm doing:

>>> lst = ['1', '1:2', '3', '-1:4']
>>> splits = []
>>> for s in lst:
... 	pair = s.split(':')
... 	if len(pair) != 2:
... 		pair.append(None)
... 	splits.append(pair)
... 	
>>> splits
[['1', None], ['1', '2'], ['3', None], ['-1', '4']]

Basically, I want to split each string into two items, substituting
None when no second item is specified in the string.  (As you can see,
in my strings, the items are delimited by ':').

It seems like a simple enough operation that I should be able to write
a list comprehension for it, but I can't figure out how...  Any
suggestions?

Steve
-- 
You can wordify anything if you just verb it.
        - Bucky Katt, Get Fuzzy



More information about the Python-list mailing list