This article will cover 4 different ways to split a string to list of characters in python.
One of these methods uses split()
function while other methods convert the string into a list without split()
function.
1. list constructor
Python list has a constructor which accepts an iterable as argument and returns a list whose elements are the elements of iterable.
An iterable is a structure that can be iterated. A string is also an iterable since it can be iterated over its characters.
Thus, a string passed to list constructor returns a list of characters of that string. Example,
str = 'codippa' l = list(str) print('List is:',l)
This prints
List is: [‘c’, ‘o’, ‘d’, ‘i’, ‘p’, ‘p’, ‘a’]
2. list comprehension
Python list comprehension can be used to convert string to list of characters as shown below.
str = 'codippa' l = [c for c in str] print('List is:',l)
Above program outputs
List is: [‘c’, ‘o’, ‘d’, ‘i’, ‘p’, ‘p’, ‘a’]
List comprehension can also be used to copy or clone a list in python.
3. List slicing
To convert a string to list of characters, we can also use list slicing as shown below.
# initialize string str = 'codippa' # initialize list l = [] # assign string to list l[:] = str print('List is:',l)
where, l[:]
is list slicing syntax.
In list slicing, start and end indexes are separated by a colon(:) in square brackets.
Remember that if we do not provide any values for these, start index is set to 0(zero) and end index is set to the last element of list.
Thus, l[:]
selects all elements of the list.
4. split() function
If the string contains a separator, then it can be converted into a list of characters with the separator removed.
Python’s inbuilt split()
function accepts a string separator as argument and returns a list of characters with the separator removed. Example,
str = 'c-o-d-i-p-p-a' # split over - l = str.split('-') print('List is:', l)
This prints
List is: [‘c’, ‘o’, ‘d’, ‘i’, ‘p’, ‘p’, ‘a’]
Hope the article was useful.