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)

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

Examples

1. Convert given string with space separated values to a 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 Code Copy

Output

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

2. Convert given string with comma separated values to a 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 Code Copy

Output

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

3. Convert given string with hyphen separated values to a 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 Code Copy

Output

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

Reference tutorials for the above program

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍