This article will cover 4 different ways to split a string into a list of characters. One of these methods uses split()
function while other methods convert the string into a list without split()
function.
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’]
Method 2: Using list comprehension
With list comprehension, an iterable can be easily converted to a list 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’]
A string can be converted to a list of characters using 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.
Method 4: Using 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’]