One task that you may have to do from time to time is to convert a string into a list of values.
This may be done in different forms, but in this article, we are going to see 2 ways.
Use split()
The first way to do that is by using the method split(). This method can be called by a string and can also accept a separator as a parameter.
If you don’t provide any separator, the default one is going to be any whitespace that is there.
Let’s take an example to illustrate this:
Since we haven’t included any separator at all, this split() method is going to detect any whitespace such as multiple spaces, tabs, and even new lines:
Use split() with separators
You can also convert strings into separators based on a custom separator of your choice that you have.
Let’s say that you get a string of comma-separated values.
As you may guess, you simply need to write a comma as the separator and you are then going to have a list of values.
Here is an example:
Use ast.literal_eval()
Let’s say that you get the input in a function that is a string, but it is supposed to be a list:
input = "[1,2,3]"
You don’t need it in that format. You need it to be a list:
input = [1,2,3]
Or maybe you the following response from an API call:
input = [[1, 2, 3], [4, 5, 6]]
Rather than bothering with complicated regular expressions, all you have to do is import the module ast and then call its method literal_eval:
That’s all you need to do.
Now you will get the result as a list, or list of lists, namely like the following:
That’s pretty much it. I hope this helps you out.