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

给定一个字符串,我们必须在Python中拆分为字符数组。

(Splitting string to characters)

1) Split string using for loop

1)使用for循环分割字符串

Use for loop to convert each character into the list and returns the list/array of the characters.

使用for循环将每个字符转换为列表并返回字符的列表/数组。

Python program to split string into array of characters using for loop

Python程序使用for循环将字符串拆分为字符数组

# 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)

2)通过将字符串转换为列表来分割字符串(使用类型转换)

We can typecast string to the list using list(string)

list(string)字符串类型转换到列表中-它会返回一个字符列表/数组。

Python program to split string into array by typecasting string to list

Python程序通过将字符串类型转换为列表将字符串拆分为数组

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