list comprehension for splitting strings into pairs

Russell Blau russblau at hotmail.com
Tue Oct 12 18:27:54 EDT 2004


"Steven Bethard" <steven.bethard at gmail.com> wrote in message
news:mailman.4781.1097619107.5135.python-list at python.org...
> 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?

How's this?

>>> lst = ['1', '1:2', '3', '-1:4']
>>> splits = [':' in item and item.split(':', 1) or [item, None] \
              for item in lst]
>>> splits
[['1', None], ['1', '2'], ['3', None], ['-1', '4']]

This approach is cute, but lacks any error-checking, so you can only use it
if you are fairly sure your "lst" will contain strings in the proper format.

-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.





More information about the Python-list mailing list