The string is a data or variable type used to store single or more characters in Python. As string may contain different characters in different formats and patterns. The string may contain a sentence with words separated with spaces or delimiter characters like commas, etc. The string variable content can be split according to these patterns and delimiters into the list type.
Convert String To List with String split() Method
Python string type provides the split() method which is used to split the string into a list according to the provided splitter or delimiter. The syntax of the split() method is like below.
- STRING is the string variable or string value that will be split.
- DELIMITER is the delimiter character that will split the string. The DELIMITER character is generally set as space, comma, etc.
The split() method returned the list data which can be printed to the screen or set into a variable.
In the following example we will use a sentence as a string where spaces are natural separators. We will use a single space as separator and convert string to list.
sentence = "I like PythonTect" list = sentence.split(" ") print(list)
The output is like below.
['I', 'like', 'PythonTect']
The split() method can be also called on a string value or string literal without defining any variable. The usage is the same with the string variable.
list = "I like PythonTect".split(" ") print(list)
Even the single space is a popular delimiter we can also used different delimiters like command. In the following example we will split the string into list according to the comma delimiter.
sentence = "I,like,PythonTect" list = sentence.split(",") print(list)
['I', 'like', 'PythonTect']
Convert String To List Character By Character
A string is a list of characters that can be none or multiple characters. The list operator can be used to convert a string into a character list. Every character in the string is converted into a list item and put into the list.
sentence = "I like PythonTect" list= list[:0]=sentence print(list)
['I', ' ', 'l', 'i', 'k', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', 'T', 'e', 'c', 't']
Convert String Type List Representation Into List
Another case for converting a string into a list is where the string is actually a list definition but in string format. The string contains the brackets, commas to delimit items, etc. The string is evaluated in Python and converted into a list and assigned into a variable which will be a list.
a = "[1,2,3,4]" print(type(a)) list = a.strip('][').split(', ') print(type(list))
<class 'str'> <class 'list'>
There is an alternative method in order to convert a string that contains a list definition. The literal_eval() method can be used to evaluate a given string like a Python script and returns the evaluated value. The literal_eval() method is provided by the ast module.
import ast a = "[1,2,3,4]" print(type(a)) list = ast.literal_eval(a) print(type(list))