2017-05-23 39 views
0

我有從bash的字符串類型列表,它看起來像這樣:轉換字符串列表,以純列表在Python

INP =「[」一」,‘二’,‘三’,‘四’, 「five」]「

輸入來自bash腳本。 在我的Python腳本,我想將其轉換爲正常的Python列表格式爲:

[「一」,「二」,「三」,「四有」,「五」]

其中所有的元素都是字符串,但是整個元素被表示爲列表。

我試過了:list(inp) 它不起作用。有什麼建議麼?

+2

有一個看看[ast.li teral_eval](https://docs.python.org/3.6/library/ast.html#ast.literal_eval)。 –

回答

3

試試這個代碼,

import ast 
inp = '["one","two","three","four","five"]' 
ast.literal_eval(inp) # will prints ['one', 'two', 'three', 'four', 'five'] 
+0

謝謝,這工作ast.literal_eval() – Pranay

3

看一看ast.literal_eval

>>> 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 
+0

謝謝,這工作ast.literal_eval() – Pranay

1

該解決方案使用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'] 
1

可以使用替換和拆分爲以下幾點:

>>> inp 
"['one','two','three','four','five']" 

>>> inp.replace('[','').replace(']','').replace('\'','').split(',') 
['one', 'two', 'three', 'four', 'five'] 
相關問題