Christian Eslabon
Christian Eslabon

Reputation: 185

Change string to list datatype

How can I change the data type from string to list and also remove the single qoutes outside?

x = '["a","b"]'
type(x)
>>> str

Desired output is

x = ["a","b"]
type(x)
>>> list

Upvotes: 2

Views: 133

Answers (4)

Mayank Porwal
Mayank Porwal

Reputation: 34046

Use eval:

In [933]: eval(x)
Out[933]: ['a', 'b']

In [934]: type(eval(x))
Out[934]: list

Upvotes: 2

0x263A
0x263A

Reputation: 1859

You could use regex to parse the string into a list:

import re
x = re.findall(r"\"(\w+)\"", '["a","b"]')
print(x, type(x))

Outputs:

['a', 'b'] <class 'list'>

Upvotes: 1

fanzhefu
fanzhefu

Reputation: 46

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

x[2:-2].split('","')

Upvotes: 0

Mark
Mark

Reputation: 92440

The string you have is valid json, so you can just parse it:

import json

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

l = json.loads(x)

print(l)
# ['a', 'b']

print(type(l))
# <class 'list'>

Upvotes: 1

Related Questions