有没有办法像分割
那样分割字符串?"The quick brown fox jumps over the lazy dog."
到
['The qu', 'ick br', 'own fo', 'x jump', 's over', ' the l', 'azy do', 'g.']
?
答案 0 :(得分:3)
如果您尝试按特定数量的字符进行拆分,请考虑将列表理解与step
的{{1}}参数一起使用:
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)
的增量,直到N
。我们可以将其用作每个切片的起始索引,然后在该索引之后使用len(x)
个字符作为N
。