Home > Net >  Convert string to list using Python
Convert string to list using Python

Time:01-20

I need to convert string like below to list using Python.

sample_str = '["sample text1", "\'sample text2\'", "sample text3"]'

If we check the data type of "sample_str" above, it will be string. I need to know if there a way I could make it a list like below :

sample_str_to_list = ["sample text1", "\'sample text2\'", "sample text3"]

If we check the data type of "sample_str_to_list" above, it will be list.

I have tried to do it using string slicing, but it did not help. Can somebody please help here. Thank in advance.

CodePudding user response:

What you have looks an awful lot like JSON:

>>> sample_str = '["sample text1", "\'sample text2\'", "sample text3"]'
>>> import json
>>> json.loads(sample_str)
['sample text1', "'sample text2'", 'sample text3']

If it's actually the representation of a Python str value, there's ast.literal_eval:

>>> import ast
>>> ast.literal_eval(sample_str)
['sample text1', "'sample text2'", 'sample text3']

If it's neither of the above, you're going to have to identify the encoding scheme and find a parser for it, or write your own.

CodePudding user response:

you could use ast.list_eval, for a safer eval

from ast import literal_eval
sample_str = '["sample text1", "\'sample text2\'", "sample text3"]'
sample_str = literal_eval(sample_str)

Output:

['sample text1', "'sample text2'", 'sample text3']

CodePudding user response:

You can try using exec

exec("""
sample_str_to_list = ["sample text1", "'sample text2'", "sample text3"]
""")
  •  Tags:  
  • Related