Reputation: 588
I have a string type list from bash which looks like this:
inp = "["one","two","three","four","five"]"
The input is coming from bash script. In my python script I would like to convert this to normal python list in this format:
["one","two","three","four","five"]
where all elements would be string, but the whole thin is represented as list.
I tried: list(inp) it does not work. Any suggestions?
Upvotes: 0
Views: 229
Reputation: 948
you can use replace and split as the following:
>>> inp
"['one','two','three','four','five']"
>>> inp.replace('[','').replace(']','').replace('\'','').split(',')
['one', 'two', 'three', 'four', 'five']
Upvotes: 2
Reputation: 92884
The solution using re.sub()
and str.split()
functions:
import re
inp = '["one","two","three","four","five"]'
l = re.sub(r'["\]\[]', '', inp).split(',')
print(l)
The output:
['one', 'two', 'three', 'four', 'five']
Upvotes: 2
Reputation: 3570
Have a look at 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']
Notice that your original input string is not a valid python string, since it ends after "["
.
>>> inp = "["one","two","three","four","five"]"
SyntaxError: invalid syntax
Upvotes: 3
Reputation: 442
Try this code,
import ast
inp = '["one","two","three","four","five"]'
ast.literal_eval(inp) # will prints ['one', 'two', 'three', 'four', 'five']
Upvotes: 3