G
G
GreenX52020-07-02 15:34:16
Python
GreenX5, 2020-07-02 15:34:16

How to add line breaks at a given interval?

There is a long string, every eg 50 characters replace the first occurring space with '\n'.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2020-07-02
@GreenX5

Looks like it should be ok

import re

def make_newlines(s, offset=50):

    iterations = len(s) // offset + 1

    for x in range(1, iterations):
        chunk = s[x*offset:]
        replaced = re.sub(r'\s', '\n', chunk, 1)
        
        s = s.replace(chunk, replaced)

    return s

G
GreenX5, 2020-07-11
@GreenX5

Found Libu

import textwrap

text = 'abcdifgh '*10
text = textwrap.fill(text, 20)
print(text)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question