gpt4 book ai didi

python - 将字符串拆分为包含许多 char pro 项目的数组

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:28 25 4
gpt4 key购买 nike

我有一个字符串,我想要一个 str 数组,例如:

"hello world"
["hel", "lo ", "wor", "ld"]

["hell", "o wo", "rld"]

我看到 list(message) 可以,但只是为了

["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", ]

有什么想法吗?

最佳答案

>>> s = 'hello world'
>>> [s[i:i+3] for i in range(len(s)) if not i % 3]
['hel', 'lo ', 'wor', 'ld']

对于更通用的解决方案(即自定义拆分),请尝试此功能:

def split_on_parts(s, *parts):
total = 0
buildstr = []
for p in parts:
buildstr.append(s[total:total+p])
total += p
return buildstr

s = 'hello world'
print split_on_parts(s, 3, 3, 3, 3)
print split_on_parts(s, 4, 3, 4)

产生输出:

['hel', 'lo ', 'wor', 'ld']
['hell', 'o w', 'orld']

或者如果您真的想要单线:

def split_on_parts(s, *parts):
return [s[sum(parts[:p]):sum(parts[:p+1])] for p in range(len(parts))]

关于python - 将字符串拆分为包含许多 char pro 项目的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4402383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com