天天看點

在Python中将字元串拆分為字元數組

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