Split string into strings by length?

后端 未结 15 2172
半阙折子戏
半阙折子戏 2020-11-27 06:31

Is there a way to take a string that is 4*x characters long, and cut it into 4 strings, each x characters long, without knowing the length of the s

15条回答
  •  佛祖请我去吃肉
    2020-11-27 07:00

    Got an re trick:

    In [28]: import re
    
    In [29]: x = "qwertyui"
    
    In [30]: [x for x in re.split(r'(\w{2})', x) if x]
    Out[30]: ['qw', 'er', 'ty', 'ui']
    

    Then be a func, it might looks like:

    def split(string, split_len):
        # Regex: `r'.{1}'` for example works for all characters
        regex = r'(.{%s})' % split_len
        return [x for x in re.split(regex, string) if x]
    

提交回复
热议问题