[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

string to list when the contents is a list

Wes James

2/17/2010 11:49:00 PM

I have been trying to create a list form a string. The string will be
a list (this is the contents will look like a list). i.e. "[]" or
"['a','b']"

The "[]" is simple since I can just check if value == "[]" then return []

But with "['a','b']" I have tried and get:

a="['a','b']"

b=a[1:-1].split(',')

returns

[ " 'a' "," 'b' " ]

when I want it to return ['a','b'].

How can I do this?

thx,

-wes
5 Answers

Rhodri James

2/18/2010 12:13:00 AM

0

On Wed, 17 Feb 2010 23:48:38 -0000, Wes James <comptekki@gmail.com> wrote:

> I have been trying to create a list form a string. The string will be
> a list (this is the contents will look like a list). i.e. "[]" or
> "['a','b']"

If your string is trusted (i.e. goes nowhere near a user), just eval() it.

--
Rhodri James *-* Wildebeeste Herder to the Masses

Steven D'Aprano

2/18/2010 12:47:00 AM

0

On Thu, 18 Feb 2010 00:13:05 +0000, Rhodri James wrote:

> On Wed, 17 Feb 2010 23:48:38 -0000, Wes James <comptekki@gmail.com>
> wrote:
>
>> I have been trying to create a list form a string. The string will be
>> a list (this is the contents will look like a list). i.e. "[]" or
>> "['a','b']"
>
> If your string is trusted (i.e. goes nowhere near a user), just eval()
> it.

Or use something like YAML or JSON to parse it.

Fredrik Lundh has a simple_eval function which should be safe to use:

http://effbot.org/zone/simple-iterator-...


But it's fairly simple to parse a simple list like this. Here's a quick
and dirty version:


def string_to_list(s):
s = s.strip()
if not s.startswith('[') and s.endswith(']'):
raise ValueError
s = s[1:-1].strip()
items = [item.strip() for item in s.split(',')]
for i, item in enumerate(items):
items[i] = dequote(item)
return items


def dequote(s):
for delimiter in ('"""', "'''", '"', "'"):
if s.startswith(delimiter) and s.endswith(delimiter):
n = len(delimiter)
return s[n:-n]
raise ValueError



>>> s = "['a','b']"
>>> print s
['a','b']
>>> string_to_list(s)
['a', 'b']
>>> x = string_to_list(s)
>>> type(x)
<type 'list'>
>>> x
['a', 'b']



--
Steven

Ben Finney

2/18/2010 12:58:00 AM

0

Wes James <comptekki@gmail.com> writes:

> I have been trying to create a list form a string. The string will be
> a list (this is the contents will look like a list). i.e. "[]" or
> "['a','b']"

Pulling back to ask about the larger problem: Are you trying to create
Python data structures from a serialised representation?

There are several well-implemented solutions, including the standard
library modules â??pickleâ?? and â??jsonâ??. Do you have control over the choice
of serialisation format?

--
\ â??I went to court for a parking ticket; I pleaded insanity. I |
`\ said â??Your Honour, who in their right mind parks in the passing |
_o__) lane?â??â? â??Steven Wright |
Ben Finney

nn

2/18/2010 2:52:00 PM

0



Wes James wrote:
> I have been trying to create a list form a string. The string will be
> a list (this is the contents will look like a list). i.e. "[]" or
> "['a','b']"
>
> The "[]" is simple since I can just check if value == "[]" then return []
>
> But with "['a','b']" I have tried and get:
>
> a="['a','b']"
>
> b=a[1:-1].split(',')
>
> returns
>
> [ " 'a' "," 'b' " ]
>
> when I want it to return ['a','b'].
>
> How can I do this?
>
> thx,
>
> -wes


I am surprised nobody gave you the simple answer yet that may even
work for your situation:

b=a[2:-2].split("','")

Rhodri James

2/19/2010 12:27:00 AM

0

On Thu, 18 Feb 2010 14:52:29 -0000, nn <pruebauno@latinmail.com> wrote:

> Wes James wrote:
>> I have been trying to create a list form a string. The string will be
>> a list (this is the contents will look like a list). i.e. "[]" or
>> "['a','b']"
>>
>> The "[]" is simple since I can just check if value == "[]" then return
>> []
>>
>> But with "['a','b']" I have tried and get:
>>
>> a="['a','b']"
>>
>> b=a[1:-1].split(',')
>>
>> returns
>>
>> [ " 'a' "," 'b' " ]
>>
>> when I want it to return ['a','b'].
>>
>> How can I do this?
>>
>> thx,
>>
>> -wes
>
>
> I am surprised nobody gave you the simple answer yet that may even
> work for your situation:
>
> b=a[2:-2].split("','")

Because it's really *very* not robust. "Harmless" whitespace defeats it
for starters, and that's one of the most likely things to vary between
example data and reality. If you trust your data to be well-formed enough
for this to work, you might as well use eval() instead. If you don't,
parsing is the only sensible answer.

--
Rhodri James *-* Wildebeeste Herder to the Masses