Convert String to List in Python

To convert a string to a list in Python:

my_list = my_string.split("separated_by")

For example, if your string is separated by spaces, then apply this syntax to convert the string with the spaces into a list (notice that a space was applied inside the brackets of the “split”):

my_string = "aa bb cc dd ee"

my_list = my_string.split(" ")

print(my_list)

The result:

['aa', 'bb', 'cc', 'dd', 'ee']

Alternatively, if your string is separated by commas, then apply the script below to convert the string with the commas into a list (notice that a comma was specified inside the brackets of the split):

my_string = "aa,bb,cc,dd,ee"

my_list = my_string.split(",")

print(my_list)

The result:

['aa', 'bb', 'cc', 'dd', 'ee']

Depending on your needs, you may specify a different separator inside the brackets of the split.

You may also want to check the following guide to learn how to convert a list to string in Python.

Leave a Comment