In Python, if you ever need to deal with codebases that perform various calls to other APIs, there may be situations where you may receive a string in a list-like format, but still not explicitly a list. In situations like these, you may want to convert the string into a list.
In this article, we will look at some ways of achieving the same on Python.
Converting List-type strings
A list-type string can be a string that has the opening and closing parenthesis as of a list and has comma-separated characters for the list elements. The only difference between that and a list is the opening and closing quotes, which signify that it is a string.
str_inp = '["Hello", "from", "AskPython"]'
Let us look at how we can convert these types of strings to a list.
Method 1: Using the ast module
ast (Abstract Syntax Tree) module is a handy tool that can be used to deal with strings like this, dealing with the contents of the given string accordingly.
We can use
ast.literal_eval() to evaluate the literal and convert it into a list.
import ast str_inp = '["Hello", "from", "AskPython"]' print(str_inp) op = ast.literal_eval(str_inp) print(op)
'["Hello", "from", "AskPython"]' ['Hello', 'from', 'AskPython']
Method 2: Using the json module
json module also provides us with methods that can manipulate strings.
In particular, the
json.loads() method is used to decode JSON-type strings and returns a list, which we can then use accordingly.
import json str_inp = '["Hello", "from", "AskPython"]' print(str_inp) op = json.loads(str_inp) print(op)
The output remains the same as before.
Method 3: Using str.replace() and str.split()
We can use Python’s in-built
str.replace() method and manually iterate through the input string.
We can remove the opening and closing parenthesis while adding elements to our newly formed list using
str.split(","), parsing the list-type string manually.
str_inp = '["Hello", "from", "AskPython"]' str1 = str_inp.replace(']','').replace('[','') op = str1.replace('"','').split(",") print(op)
['Hello', ' from', ' AskPython']
Converting Comma separated Strings
A comma-separated string is a string that has a sequence of characters, separated by a comma, and enclosed in Python’s string quotations.
str_inp = "Hello,from,AskPython'
To convert these types of strings to a list of elements, we have some other ways of performing the task.
Method 1: Using str.split(‘,’)
We can directly convert it into a list by separating out the commas using
str_inp = "Hello,from,AskPython" op = str_inp.split(",") print(op)
['Hello', 'from', 'AskPython']
Method 2: Using eval()
If the input string is trusted, we can spin up an interactive shell and directly evaluate the string using
However, this is NOT recommended, and should rather be avoided, due to security hazards of running potentially untrusted code.
Even so, if you still want to use this, go ahead. We warned you!
str_inp = "potentially,untrusted,code" # Convert to a quoted string so that # we can use eval() to convert it into # a normal string str_inp = "'" + str_inp + "'" str_eval = '' # Enclose every comma within single quotes # so that eval() can separate them for i in str_inp: if i == ',': i = "','" str_eval += i op = eval('[' + str_eval + ']') print(op)
The output will be a list, since the string has been evaluated and a parenthesis has been inserted to now signify that it
op is a list.
['potentially', 'untrusted', 'code']
This is quite long and is not recommended for parsing out comma-separated strings. Using
str.split(',') is the obvious choice in this case.
In this article, we learned some ways of converting a list into a string. We dealt with list-type strings and comma-separated strings and converted them into Python lists.