To convert a string into a list using Python, the easiest way is with the list() function.
string = "string"
l = list(string)
print(l)
#Output:
['s', 't', 'r', 'i', 'n', 'g']
If you want to convert a string into a list of elements with a delimiter, you can use the split() function.
string = "this is a string with spaces"
l = string.split()
print(l)
#Output:
['this', 'is', 'a', 'string', 'with', 'spaces']
Another way you can convert a string into a list is with comprehension.
string = "string"
l = [char for char in string]
print(l)
#Output:
['s', 't', 'r', 'i', 'n', 'g']
When working with different objects in Python, the ability to be able convert objects into other objects easily can be useful.
One such case is if you want to convert a string into a list in Python.
To convert a string into a list using Python, the easiest way is with the list() function.
list() creates a new list with elements containing each character of the string.
Below is a simple example showing you how to convert a string to a list in Python.
string = "string"
l = list(string)
print(l)
#Output:
['s', 't', 'r', 'i', 'n', 'g']
Using split() to Split String by Delimiter into List Using Python
A very useful function in Python is the split() function.
By default, split() converts a string into a list where each item is the words of the string.
You can also use split() to split a string by a different delimiter.
With split(), you can convert a string into a list.
For example, if you wanted to split a list by the spaces, then you can use split() in the following way.
string = "this is a string with spaces"
l = string.split()
print(l)
#Output:
['this', 'is', 'a', 'string', 'with', 'spaces']
Using Comprehension to Convert String to List in Python
One other way you can convert a string to a list is with comprehension.
With comprehension, you can loop over each character in a string and add it to a list.
Below is how you can use comprehension to convert a string into a list of the characters in Python.
string = "string"
l = [char for char in string]
print(l)
#Output:
['s', 't', 'r', 'i', 'n', 'g']
Hopefully this article has been useful for you to learn how to convert strings to lists in Python.