Splitting a string using space delimiters and a maximum length

后端 未结 3 1086
遇见更好的自我
遇见更好的自我 2021-01-11 21:44

I\'d like to split a string in a similar way to .split() (so resulting in a list) but in a more intelligent way: I\'d like it to split it into chunks that are u

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-11 21:59

    You're probably looking to use a regex. The python re module has a split function, but I think you would be better served by simply matching groups.

    >>> re.findall(r'(.{,15})\s(.*$)', 'A string wth words')
    [('A string wth', 'words')]
    

    [Edit] sorry, missed the point where you want multiple chunks. I was going to put a more complex regex in here, but the textwrap module cited above is made for this. I'll leave extending the regex as an exercise for you if you choose.

提交回复
热议问题