How to Convert String to Character Array in Python
In this article, we will learn to convert a given string into an array of characters in Python. We will use some built-in functions and some custom codes as well. Let's first have a quick look over what is a string in Python.
Python String
The string is a type in python language just like integer, float, boolean, etc. Data surrounded by single quotes or double quotes are said to be a string. A string is also known as a sequence of characters.
string1 = "apple"
string2 = "Preeti125"
string3 = "12345"
string4 = "pre@12"
Converting a string to a character array basically means splitting each character. This comma-separated character array will be a list of characters. List prints a string into comma-separated values. Each character will represent each index value.
Let us look at the different ways below to convert a string to a character array.
Example: Convert String to Character Array Using For loop
This example uses for loop to convert each character of string into comma-separated values. It prints a list of characters separated by a comma. It encloses the for loop within square brackets []
and splits the characters of the given string into a list of characters.
string = "studytonight"
to_array = [char for char in string]
print(to_array)
['s', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't']
Example: Convert String to Character Array Using list
This example uses list
keyword to convert a string to a character array. We can use a list to convert to any iterable. This is known as typecasting of one type to another. Python built-in list()
function typecast the given string into a list. list() takes the string as an argument and internally changes it to an array.
string = "studytonight"
to_array = list(string)
print(to_array)
['s', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't']
Example: Convert String to Character Array Using extend()
This method uses extend()
to convert string to a character array. It initializes an empty array to store the characters. extends() uses for loop to iterate over the string and adds elements one by one to the empty string. The empty string prints a list of characters.
string = "studytonight"
#empty string
to_array = []
for x in string:
to_array.extend(x)
print(to_array)
['s', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't']
Conclusion
In this article, we learned to convert a given string into a character array. We used three approaches for the conversion such as for loop
, list()
and extend()
. We used custom codes as well to understand the working.