Python Program – Convert String to List

Convert String to List

Given a string where the values are separated by a delimiter or a separator, we may need to convert this string into a list of values.

To convert a string of values separated by a separator string or character, we can use String.split() method.

Call the split() method on the given string, and pass the delimiter or separator as argument to split() method, as shown in the following. split() method returns a list of values.

string.split(delimiter)
Run

Where delimiter is a string. If no delimiter is provided, then the split() method splits the string with whitespace as delimiter.

Convert string with space separated values to list

Given a string where values are separated by space character. In the following program, we convert this string into a list.

Python Program

myString = 'apple banana cherry'
myList = myString.split()
print(myList)
Run

Output

['apple', 'banana', 'cherry']

Convert string with comma separated values to list

Given a string where values are separated by comma character. In the following program, we convert this string into a list by using split() method and comma ',' character as delimiter or separator.

Python Program

myString = 'apple,banana,cherry'
myList = myString.split(',')
print(myList)
Run

Output

['apple', 'banana', 'cherry']

Convert string with hyphen separated values to list

Given a string where values are separated by hyphen character. In the following program, we convert this string into a list by using split() method and hyphen '-' character as delimiter or separator.

Python Program

myString = 'apple-banana-herry'
myList = myString.split('-')
print(myList)
Run

Output

['apple', 'banana', 'cherry']

Reference

Summary

In this tutorial of Python Examples, we learned how to convert a given string into a list of values using String.split() method.