Search code examples
pythonregexstringcountline-breaks

Insert a line-break every n characters, reset n on line-break using Python


I get a block of text from the Jira REST-Api. I need to insert a line break every 150 characters.

If the 150th character is not a whitespace insert the line break into the last whitespace, that count should reset if that text contains a line break.

i've tried it with regex, but it deletes/ignores the line breaks already in the text and it inserts line breaks in the middle of words

featureText = re.sub("(.{150})", "\\1\n", featureText, 0, re.DOTALL)
#featureText contains some text from the api get request

for simplicity's sake let's say i want to add a linebreak every 10 characters. and i have the text

My Television is broken
and that sucks

i currently get

My Televis
ion is bro
ken and th
at sucks

what i want is

My
Television
is broken
and that
sucks

Edit: Clarified my question for it to be loser to the real world. Only the example uses 10 characters, my real problem uses 150 characters so don't worry about cutting a word in half, i guess there won't be any word that is 150 characters long.


Solution

  • I would use textwrap like this:

    import textwrap
    
    example = textwrap.dedent("""\
        My Television is broken
        and that sucks""")
    
    print '\n'.join(l for line in example.splitlines() 
                      for l in textwrap.wrap(line, width=10))
    

    This results in:

    My
    Television
    is broken
    and that
    sucks
    

    A better example is:

    example = textwrap.dedent("""\
        My Television is
        and that sucks""")
    

    Which results in:

    My
    Television
    is
    and that
    sucks
    

    This better shows that the original lines are individually wrapped.