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) – it will return a list/array of characters.
我們可以使用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', '!']
翻譯自: https://www.includehelp.com/python/split-a-string-into-array-of-characters.aspx