This last solution will work on any list stored as a string, nested or not. # Flatten and split the non nested list items # Look ahead for the bracketed text that signifies nested list # Clean it up so the regular expression is simpler 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: import re 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): x = ']' If you have nested lists, it does get a bit more annoying. Using the list () function: mystring 'hello' mylist list (mystring) print (mylist) Output: 'h', 'e', 'l', 'l', 'o' 2. ![]() In this article, we will look at some ways of achieving the same on Python. You can convert a string to a list in Python by using the list () function, or by using a list comprehension or a loop. ![]() You can parse and clean up this list as needed using list comprehension. In situations like these, you may want to convert the string into a list. # Replace, as split will otherwise retain the quotes in the returned list # String indexing to eliminate the brackets. You can do this in one line for most basic use cases, including the one given in the original question. There isn't any need to import anything or to evaluate. for the type of workloads I use Python for I usually value readability over a slightly more performant option, but as usual it depends. there are trade-offs to consider when going with the most readable option. I was disappointed to see what I considered the method with the worst readability was the method with the best performance. Timeit.timeit(stmt="list(map(str.strip, json.loads(u'')))", setup='import json', number=100000) Timeit.timeit(stmt="list(map(str.strip, ast.literal_eval(u'')))", setup='import ast', number=100000) List(map(str.strip, ast.literal_eval(u''))) split it with the separator as white spaces.Inspired from some of the answers above that work with base Python packages I compared the performance of a few (using Python 3.7.3): Let’s look at a simple example where we want to convert a string to a list of words i.e. Example 1: Convert String to List in Python Using Split() Function The split() breaks the string at the separator and returns a list of strings. Let’s know about the split() function of Python.ĭefinition of python split() function :- The pyhon split() function/method splits a given string into the python list. String to List of Strings When we need to convert a string to a list in Python containing the constituent strings of the parent string (previously separated by some separator like ‘,’ or space), we use this method to accomplish the task. Python programming uses the split() function of Python to convert a string to a list. ![]()
0 Comments
Leave a Reply. |