Skip to Content

2 ways to covert string to list in Python

2 ways to covert string to list in Python

Using Split() to convert string to list in Python

In Python, the split() method is used to split a string into a list of substrings based on a specified delimiter. Here’s an example of how you can use the split() method to convert a string to a list:

string = "Hello,World,Python"
delimiter = ","
my_list = string.split(delimiter)
print(my_list)

['Hello', 'World', 'Python']

In the example above, we have a string “Hello,World,Python” and we want to split it into a list based on the comma (,) delimiter.

By calling the split(delimiter) method on the string, we obtain a list my_list where each element corresponds to a substring between the delimiters.

In this case, the resulting list [‘Hello’, ‘World’, ‘Python’] contains three elements.

You can choose any delimiter to split the string, such as a space, a hyphen, or any other character or sequence of characters. If no delimiter is specified, the split() method will split the string at whitespace by default.

Note that the split() method returns a list of strings. If you need to convert the elements of the list to a different data type, you can do so using appropriate conversions after splitting the string.

str= "Hire the top 1% freelance developers"
list= str.split()
print(list)

Output:

['Hire', 'the', 'top', '1%', 'freelance', 'developers']

Using list() to convert string to list in Python

As aforementioned, this method converts a string into a list of characters. Hence this method is not used quite often.

I would recommend using this method only if you are certain that the list should contain each character as an item and if the string contains a set of characters or numbers that are not divided by a space. If not, the spaces would also be considered as a character and stored in a list.

str= "Hire freelance developers"
list= list(str.strip(" "))
print(list)

Output:

['H', 'i', 'r', 'e', ' ', 'f', 'r', 'e', 'e', 'l', 'a', 'n', 'c', 'e', ' ', 'd', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r', 's']

Keep in mind that the list() constructor treats the input string as an iterable and creates a list with each character as a separate element. If you want to split the string based on a specific delimiter, you should use the split() method as mentioned earlier.