In this tutorial, we will look at how to convert a string in Python to a list with the help of some examples.
How to convert a string to a list?
There are two common use cases for converting a string to a list in Python –
- Split the string by a delimiter (for example, a whitespace character) and get a list of strings resulting from the split.
- Split the string into a list of its constituent characters.
Let’s look at the above two use-cases in detail with the help of some examples.
List to string using string
You can use the string
split() function to get a list of strings resulting from splitting the original string on the occurrence of a delimiter.
Let’s look at an example –
# create a string s = "This is Sparta!" # list from string with split() ls = s.split() print(ls)
['This', 'is', 'Sparta!']
By default the
split() function splits the string by a whitespace character. You can see that we get the words in the above string in a list.
String to list using
You can use the Python built-in
list() function to get a list of the string characters from a string. Pass the string as an argument to the
Let’s look at an example. We will use the same string that we used in the example above to see the difference between the two methods and what they are intended for.
# create a string s = "This is Sparta!" # list from string with list() ls = list(s) print(ls)
['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'S', 'p', 'a', 'r', 't', 'a', '!']
The resulting list contains each string character as a separate element.
In this tutorial, we looked at two different methods to get a list from a string depending upon your specific use case.
- To split a string into a list of strings by a delimiter, use the string
- To get each character in the string as a list element, use the
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.