Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

format text to limit the number of columns

I’m looking for a way to format long text strings, by inserting new lines (or splitting) so that each part doesn’t exceed a fixed length. For example, this input:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc interdum mattis quam, id elementum tortor condimentum sit amet. Aliquam quam erat, suscipit ut dui ac, laoreet varius neque. Nulla commodo, arcu ut finibus tempor, leo lorem tempus tortor, et consectetur mi nisl sed ante.

would give, if limited to 80 chars, something like that:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc interdum mattis
quam, id elementum tortor condimentum sit amet. Aliquam quam erat, suscipit ut
dui ac, laoreet varius neque. Nulla commodo, arcu ut finibus tempor, leo lorem
tempus tortor, et consectetur mi nisl sed ante.

Is there anything in the standard library, or in a reasonable dependency, allowing to do something like that?
If not, I can code something, but I’d be surprised if no one had already solved this kind of issue…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you ^^

>Solution :

You can use this module called textwrap3 whichI find very helpful when i use python.

from textwrap3 import wrap

text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc interdum mattis quam, id elementum tortor condimentum sit amet. Aliquam quam erat, suscipit ut dui ac, laoreet varius neque. Nulla commodo, arcu ut finibus tempor, leo lorem tempus tortor, et consectetur mi nisl sed ante.'

sentence = wrap(text, 80)

for x in sentence:
    print(x)
Outputs:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc interdum mattis
quam, id elementum tortor condimentum sit amet. Aliquam quam erat, suscipit ut
dui ac, laoreet varius neque. Nulla commodo, arcu ut finibus tempor, leo lorem
tempus tortor, et consectetur mi nisl sed ante.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading