我有一个来自bash的字符串类型列表,如下所示:
inp =" ["一个","两个","三个","四个"," 5"]"
输入来自bash脚本。 在我的python脚本中,我想以这种格式将其转换为普通的python列表:
[&#34;一个&#34;&#34; 2&#34;&#34;三&#34;&#34; 4&#34;&#34; 5&#34;] < / p>
其中所有元素都是字符串,但整个thin表示为list。
我试过:list(inp) 这是行不通的。有什么建议吗?
答案 0 :(得分:3)
试试这段代码,
import ast
inp = '["one","two","three","four","five"]'
ast.literal_eval(inp) # will prints ['one', 'two', 'three', 'four', 'five']
答案 1 :(得分:3)
>>> import ast
>>> inp = '["one","two","three","four","five"]'
>>> converted_inp = ast.literal_eval(inp)
>>> type(converted_inp)
<class 'list'>
>>> print(converted_inp)
['one', 'two', 'three', 'four', 'five']
请注意,您的原始输入字符串不是有效的python字符串,因为它在"["
之后结束。
>>> inp = "["one","two","three","four","five"]"
SyntaxError: invalid syntax
答案 2 :(得分:2)
使用re.sub()
和str.split()
函数的解决方案:
import re
inp = '["one","two","three","four","five"]'
l = re.sub(r'["\]\[]', '', inp).split(',')
print(l)
输出:
['one', 'two', 'three', 'four', 'five']
答案 3 :(得分:2)
您可以使用replace和split作为以下内容:
>>> inp
"['one','two','three','four','five']"
>>> inp.replace('[','').replace(']','').replace('\'','').split(',')
['one', 'two', 'three', 'four', 'five']