Splitting a string using space delimiters and a maximum length

后端 未结 3 1058
遇见更好的自我
遇见更好的自我 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:57

    You can do this two different ways:

    >>> import re, textwrap
    >>> s = 'A string with words'
    >>> textwrap.wrap(s, 15)
    ['A string with', 'words']
    >>> re.findall(r'\b.{1,15}\b', s)
    ['A string with ', 'words']
    

    Note the slight difference in space handling.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-11 22:14
    >>> import textwrap
    >>> string = 'A string with words'
    >>> textwrap.wrap(string,15)
    ['A string with', 'words']
    
    0 讨论(0)
提交回复
热议问题