Re: Stringified list back to list of ints
On Wed, 12 Dec 2007 10:38:56 -0500, Calvin Spealman wrote: > I still hold my vote that if you need to reverse the "stringification" > of a list, you shouldn't have stringified the list and lost hold of the > original list in the first place. That is the solution above all others. Naturally, but it isn't always an option. Perhaps the list was read from a human-writable config file or something. It's a non-starter to expect people to write a list of ints in Python's native binary format -- and you still have the problem of how do you get those bytes from the file into Python's virtual machine and correctly bound to a name. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Stringified list back to list of ints
Another solution, possibly safer: >>> from cStringIO import StringIO >>> import csv >>> s = "[16, 16, 2, 16, 2, 16, 8, 16]" >>> sf = StringIO(s.strip()[1:-1]) >>> list(csv.reader(sf)) [['16', ' 16', ' 2', ' 16', ' 2', ' 16', ' 8', ' 16']] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Stringified list back to list of ints
I still hold my vote that if you need to reverse the "stringification" of a list, you shouldn't have stringified the list and lost hold of the original list in the first place. That is the solution above all others. On Dec 12, 2007, at 10:26 AM, Paul McGuire wrote: > On Dec 12, 7:25 am, Lee Capps <[EMAIL PROTECTED]> 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 > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Stringified list back to list of ints
On Dec 12, 7:25 am, Lee Capps <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list