Stringified list back to list of ints

Paul McGuire ptmcg at austin.rr.com
Wed Dec 12 10:26:15 EST 2007


On Dec 12, 7:25 am, Lee Capps <lca... at cteresource.org> wrote:
> Regular expressions might be a good way to handle this.
>
> import re
>
> s = '[16, 16, 2, 16, 2, 16, 8, 16]'
> get_numbers = re.compile('\d\d*').findall
>
> numbers = [int(x) for x in get_numbers(s)]
>

Isn't '\d\d*' the same as '\d+' ?

And why would you invoke re's when str.split(',') (after stripping
leading and trailing []'s) does the job so well?

numbers = map(int, s.strip('[]').split(','))

Or if map is not to your liking:

numbers = [int(x) for x in s.strip('[]').split(',')]

-- Paul



More information about the Python-list mailing list