arsenal88
arsenal88

Reputation: 1160

Turn a string into list elements

I have a string array returned from a database that needs parsing:

x = "[SD, 1G, 2G, 3G+]"

If they were integers I could do:

json.loads(x) and return a list of elements, however due to them being characters I can't.

Is there an easy implementation for this?

desired output: ['SD', '1G', '2G', '3G+'] (type: list)

Upvotes: 1

Views: 63

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22370

You can use str.split() assuming that you are sure there will never be any surrounding whitespace:

>>> x = "[SD, 1G, 2G, 3G+]"
>>> xs = x[1:-1].split(", ")
>>> xs
['SD', '1G', '2G', '3G+']

If there is a possibility for that you could call str.strip() on x beforehand:

>>> x = " [SD, 1G, 2G, 3G+]   "
>>> xs = x.strip()[1:-1].split(", ")
>>> xs
['SD', '1G', '2G', '3G+']

Upvotes: 5

I'mahdi
I'mahdi

Reputation: 24049

What about just use yaml:

(You need pip install pyyaml)

>>> import yaml
>>> s = "[SD, 1G, 2G, 3G+]"
>>> yaml.safe_load(s)
['SD', '1G', '2G', '3G+']

Upvotes: 2

Related Questions