Pranay
Pranay

Reputation: 588

Converting String list to pure list in Python

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

Answers (4)

Walid Da.
Walid Da.

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

RomanPerekhrest
RomanPerekhrest

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

Christian König
Christian König

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

Deivanai Subramanian
Deivanai Subramanian

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

Related Questions