我需要使用Python将如下所示的字符串转换为list。
sample_str = '["sample text1", "\'sample text2\'", "sample text3"]'如果我们检查上面"sample_str“的数据类型,它将是字符串。我需要知道是否有办法把它列成如下清单:
sample_str_to_list = ["sample text1", "\'sample text2\'", "sample text3"]如果我们检查上面"sample_str_to_list“的数据类型,它将是列表。
我试过用字符串切片来做它,但是它没有帮助。有人能帮帮我吗。提前谢谢。
发布于 2022-01-19 15:01:11
您所拥有的非常类似于JSON:
>>> sample_str = '["sample text1", "\'sample text2\'", "sample text3"]'
>>> import json
>>> json.loads(sample_str)
['sample text1', "'sample text2'", 'sample text3']如果它实际上是Python str值的表示,那么就有ast.literal_eval
>>> import ast
>>> ast.literal_eval(sample_str)
['sample text1', "'sample text2'", 'sample text3']如果两者都没有,则必须标识编码方案并为其找到解析器,或者编写自己的解析器。
发布于 2022-01-19 14:56:48
您可以使用ast.list_eval,以获得更安全的eval
from ast import literal_eval
sample_str = '["sample text1", "\'sample text2\'", "sample text3"]'
sample_str = literal_eval(sample_str)输出:
['sample text1', "'sample text2'", 'sample text3']发布于 2022-01-19 14:58:47
您可以尝试使用exec
exec("""
sample_str_to_list = ["sample text1", "'sample text2'", "sample text3"]
""")https://stackoverflow.com/questions/70772786
复制相似问题