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)
CodePudding user response:
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 ']
CodePudding user response:
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 ']