Contents
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.
Related Tutorials
- Python – List of Strings
- Python List without Last Element
- Python – Check if Element is in List
- Python List with First N Elements
- Python List – Add Item
- Python Program to Find Largest Number in a List
- How to Insert Item at Specific Index in Python List?
- How to Reverse Python List?
- How to Get List of all Files in Directory and Sub-directories?
- How to Check if Python List is Empty?