View Discussion Show Improve Article Save Article View Discussion Improve Article Save Article Many times, we come over the dumped data that is found in the string format and we require it to be represented into the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to list to perform tasks are quite common in web development. Let’s discuss certain ways in which this can be performed. Method #1: Using
Output: initial string [1, 2, 3, 4, 5] <class 'str'> final list ['1', '2', '3', '4', '5'] <class 'list'>
Output: initial string [1, 2, 3, 4, 5] <class 'str'> final list [1, 2, 3, 4, 5] <class 'list'>
Output: initial string [1, 2, 3, 4, 5] <class 'str'> final list [1, 2, 3, 4, 5] <class 'list'> There isn't any need to import anything or to evaluate. You can do this in one line for most basic use cases, including the one given in the original question. One liner
Explanation
Outputs:
You can parse and clean up this list as needed using list comprehension.
Nested listsIf you have nested lists, it does get a bit more annoying. Without using regex (which would simplify the replace), and assuming you want to return a flattened list (and the zen of python says flat is better than nested):
If you need to retain the nested list it gets a bit uglier, but it can still be done just with regular expressions and list comprehension:
This last solution will work on any list stored as a string, nested or not. How do I convert a string to a list in Python?The split() method is the recommended and most common method used to convert string to list in Python.
How do I convert a string to a list that looks like a list in Python?How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
How do I convert a list of strings to a list of objects?Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);
How do you convert a list of strings to a list of numbers?The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.
|