有没有办法像拆分一样拆分字符串"The quick brown fox jumps over the lazy dog."至['The qu', 'ick br', 'own fo', 'x jump', 's over', ' the l', 'azy do', 'g.']?
1 回答

米脂
TA贡献1836条经验 获得超3个赞
如果您尝试按特定数量的字符拆分,请考虑在step参数旁边使用列表推导式range:
>>> x = "The quick brown fox jumps over the lazy dog."
>>> N = 6
>>> [x[i:i+N] for i in range(0, len(x), N)]
['The qu', 'ick br', 'own fo', 'x jump', 's over', ' the l', 'azy do', 'g.']
>>>
range(0, len(x), N)将返回Nuntil的增量len(x)。我们可以将其用作每个切片的起始索引,然后N在该索引之后获取字符,如x[i:i+N].
添加回答
举报
0/150
提交
取消