在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

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值