Q:

Split a string into array of characters in Python

belongs to collection: Python String Programs

0

Split a string into array of characters in Python

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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', '!']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program for slicing a string... >>
<< Python program to reverse a string using stack and...