说明

  1. length = 2
  2. s = '1234567'
  3. # target: ['12', '34', '56', '7']
  4. length = 3
  5. s = '1234567'
  6. # target: ['123', '456', '7']

方法

  1. # 方法1
  2. import textwrap
  3. textwrap.fill(s, length).split()
  4. # 方法2
  5. [s[i:i+2] for i in range(0, len(s), length)]
  6. # 方法3
  7. import re
  8. [x for x in re.split(r'(.{%d})' % length, s) if x]
  9. [x for x in re.split(rf'(.{{{length}}})', s) if x]
  10. # 方法4
  11. from functools import partial
  12. from io import StringIO
  13. [x for x in iter(partial(StringIO(s).read, length), '')]