Home »
Python »
Python programs
Split a string into array of characters in Python
By IncludeHelp Last updated : February 13, 2024
Problem statement
Given a string, write a Python program to split the given string into array of characters.
Splitting string into array of characters
You can follow the following different approaches to split a string into array of characters:
- By using the loop
- By converting string to the list
Split string into array of characters using for loop
Use for loop to convert each character into the list and returns the list/array of the characters.
Python program to split string into array of characters using for loop
# Split string using for loop
# function to split string
def split_str(s):
return [ch for ch in s]
# main code
string = "Hello world!"
print("string: ", string)
print("split string...")
print(split_str(string))
The output of the above program is:
string: Hello world!
split string...
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
Split string into array of characters by converting string to the list
We can typecast string to the list using list(string) – it will return a list/array of characters.
Python program to split string into array by typecasting string to list
# Split string by typecasting
# from string to list
# function to split string
def split_str(s):
return list(s)
# main code
string = "Hello world!"
print("string: ", string)
print("split string...")
print(split_str(string))
The output of the above program is:
string: Hello world!
split string...
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
Python String Programs »
To understand the above programs, you should have the basic knowledge of the following Python topics: