Home » Python » Python programs

Split a string into array of characters in Python

Python | splitting string into array of characters: Here, we are going to learn how to split a given string into list of characters (array of characters) in Python?
Submitted by IncludeHelp, on May 25, 2019

Given a string and we have to split into array of characters in Python.

Splitting string to characters

1) Split string 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))

Output

string:  Hello world!
split string...
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']

2) Split string by converting string to the list (using typecast)

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))
string:  Hello world!
split string...
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.