按给定字母数分割字符串

时间:2020-05-29 22:44:13

标签: python

有没有办法像分割

那样分割字符串?
"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 个答案:

答案 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