Split String to Char Array in Python
-
Use the
for
Loop to Split a String Into Char Array in Python -
Use the
list()
Function to Split a String Into Char Array in Python -
Use the
extend()
Function to Split a String Into Char Array in Python -
Use the
unpack
Method to Split a String Into Char Array in Python - Use the List Comprehension Method to Split a String Into Char Array in Python
This tutorial, we learn how to split a string into a list of characters.
Use the for
Loop to Split a String Into Char Array in Python
In this method, we use the for
loop to iterate over the string and append each character to an empty list. See the following example code.
word = 'Sample'
lst = []
for i in word:
lst.append(i)
print(lst)
Output:
['S', 'a', 'm', 'p', 'l', 'e']
Use the list()
Function to Split a String Into Char Array in Python
Typecasting refers to the process of converting a datatype to some other datatype. We can typecast a string to a list using the list()
function which splits the string to a char array. For example,
word = 'Sample'
lst = list(word)
print(lst)
Output:
['S', 'a', 'm', 'p', 'l', 'e']
Use the extend()
Function to Split a String Into Char Array in Python
The extend()
function adds elements from an iterable object like a list, tuple, and more to the end of a given list. Since a string is a collection of characters, we can use it with the extend()
function to store each character at the end of a list. For example,
lst = []
word = 'Sample'
lst.extend(word)
print(lst)
Output:
['S', 'a', 'm', 'p', 'l', 'e']
Use the unpack
Method to Split a String Into Char Array in Python
The *
operator can be used to perform unpacking operations on objects in Python. This method unpacks a string and stores its characters in a list, as shown below.
word = "Sample"
print([*word])
Output:
['S', 'a', 'm', 'p', 'l', 'e']
Use the List Comprehension Method to Split a String Into Char Array in Python
List Comprehension is an elegant way of creating lists in a single line of code. In the method shown below, we use the for
loop to iterate over the list and store each element.
word = "Sample"
lst = [x for x in word]
print(lst)
Output:
['S', 'a', 'm', 'p', 'l', 'e']