list comprehension for splitting strings into pairs

Bob Follek bob at codeblitz.com
Tue Oct 12 18:50:05 EDT 2004


On Tue, 12 Oct 2004 16:11:45 -0600, Steven Bethard
<steven.bethard at gmail.com> wrote:

>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

Here's a pretty nasty approach:

>>> lst = ['1', '1:2', '3', '-1:4']
>>> splits = [(e.split(':') + [None])[:2] for e in lst]
>>> splits
[['1', None], ['1', '2'], ['3', None], ['-1', '4']]
--

Bob Follek
bob at codeblitz.com



More information about the Python-list mailing list