Home > OS >  Change string to list datatype
Change string to list datatype

Time:05-31

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

CodePudding user response:

Use eval:

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

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

CodePudding user response:

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'>

CodePudding user response:

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'>

CodePudding user response:

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

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