![]() |
VOOZH | about |
Sometimes we may have a string that looks like a list but is just text. We might want to convert that string into a real list in Python. The easiest way to convert a string that looks like a list into a list is by using the json module. This function will evaluate the string written as JSON list as a Python list. If the string is in JSON format (which looks like a Python list), we can use json.loads().
['Geeks', 'for', 'Geeks']
Table of Content
eval() is a built-in function that evaluates the data type from the string and changes the string to that data type.
['Geeks', 'for', 'Geeks']
The map() function applies a given function to each item in an iterable. We can use map() to convert a string into a list, especially if we need to apply a transformation (e.g., stripping spaces or changing case).
['["Geeks"', '"for"', '"Geeks"]']
If we want full control over how the string is converted, we can manually loop through the string and build the list item by item.
['Geeks', 'for', 'Geeks']
For safety, ast.literal_eval() is a better option than eval() as it only allows Python literals like lists, strings, numbers, etc. This makes it safer to use with untrusted inputs.
['Geeks', 'for', 'Geeks']