我需要使用 Python 將下面的字串轉換為串列。
sample_str = '["sample text1", "\'sample text2\'", "sample text3"]'
如果我們檢查上面“sample_str”的資料型別,它將是字串。我需要知道是否有辦法將其列在下面的串列中:
sample_str_to_list = ["sample text1", "\'sample text2\'", "sample text3"]
如果我們檢查上面“sample_str_to_list”的資料型別,它將是串列。
我曾嘗試使用字串切片來做到這一點,但它沒有幫助。有人可以在這里幫忙嗎?預先感謝。
uj5u.com熱心網友回復:
你所擁有的看起來很像 JSON:
>>> sample_str = '["sample text1", "\'sample text2\'", "sample text3"]'
>>> import json
>>> json.loads(sample_str)
['sample text1', "'sample text2'", 'sample text3']
如果它實際上是 Pythonstr值的表示,則有ast.literal_eval:
>>> import ast
>>> ast.literal_eval(sample_str)
['sample text1', "'sample text2'", 'sample text3']
如果以上都不是,您將不得不識別編碼方案并為其找到決議器,或者撰寫自己的決議器。
uj5u.com熱心網友回復:
你可以使用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']
uj5u.com熱心網友回復:
您可以嘗試使用exec
exec("""
sample_str_to_list = ["sample text1", "'sample text2'", "sample text3"]
""")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/415628.html
標籤:
