When you are working on a project, you come across a task in which you have to create the characters of a list based on the string. You can create a list based on an input string from either an API or a processed string.
Python String to List of Characters
To convert a string to list of characters in Python, use the list() method to typecast the string into a list. The list() constructor builds a list directly from an iterable, and since the string is iterable, you can construct a list from it.
def stringToList(data): return list(data) data = 'SPIDER-MAN' print(stringToList(data))
['S', 'P', 'I', 'D', 'E', 'R', '-', 'M', 'A', 'N']
We applied a list() function on a string, and it returns a list of all the characters present in the string in the same order as the string’s characters.
The SPIDER-MAN string becomes an individual element of the list, and it preserves the order of the string.
Using List comprehension
List comprehension in Python is frequently used to create a new list, where each list item is the result of some operation applied to each member of a string. You can take any iterable as an input, returning the list.
The list comprehension helps us to convert each character into a list. In addition, list comprehension delivers a shorter syntax when you create a new list based on the existing values.
def stringToList(data): return [char for char in data] data = 'NO WAY HOME' print(stringToList(data))
['N', 'O', ' ', 'W', 'A', 'Y', ' ', 'H', 'O', 'M', 'E']
In this example, the string has some spaces. That’s why we got a list with empty elements. Be aware that any spaces in the line will be included in this list cause they will cause an unexpected output or error.