0

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?

1

4 Answers 4

3

Try this code,

import ast
inp = '["one","two","three","four","five"]'
ast.literal_eval(inp) # will prints ['one', 'two', 'three', 'four', 'five']
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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']

Comments

2

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.