This concise, example-based article walks you through four different ways to turn a given string into a list in Python. Life is short, and time is precious; let’s get to the point.
Using the str.split() method
f you want to split a string into substrings based on a specific delimiter, you can use the str.split()
method. This method returns a list of substrings. The separator can be empty, a space, a comma, or any other character that you want to use as a delimiter.
Example:
text = "Welcome to Sling Academy"
# split the text into words
words = text.split()
print(words)
Output:
['Welcome', 'to', 'Sling', 'Academy']
Using the list() function
The list()
function can turn a string into a list whose each element is a character from the input string.
Example:
text = "ABCDEF"
characters = list(text)
print(characters)
Output:
['A', 'B', 'C', 'D', 'E', 'F']
Using list comprehension
List comprehension gives us a concise way to convert a string into a list by iterating over each character in the string.
Example:
my_string = "abcdefghijk"
my_list = [char for char in my_string]
print(my_list)
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
Using a for…in loop
A for...in
loop can be used to solve many tasks related to strings and lists in Python, including the task of converting a string into a list.
Example:
my_string = "abcdefghijk"
my_list = []
for letter in my_string:
my_list.append(letter)
print(my_list)
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']