Florestan Korp
Florestan Korp

Reputation: 709

Format console output in Python to have fixed width

I'm building a CLI and want to format my output to be max 60 characters wide. I don't want to hyphenate, but move the word to the next line if it is too long and don't want to manually insert \n characters in my text to achieve this goal. I have been playing around with Pthons .format() function, but to no avail.

Example: Line in output should end after 'blurry':

===================== IMAGE-DELETE CLI =====================


Welcome to the IMAGE-DELETE CLI. Based on your input blurry and under / overexposed images will be deleted and to free up some disk space.


Lets get started...

Upvotes: 0

Views: 1198

Answers (1)

ComedicChimera
ComedicChimera

Reputation: 476

Use the textwrap module.

import textwrap

lines = textwrap.wrap(text, width=60) # text is the variable contains what you want to print out

# then print it out
for line in lines:
    print(line)

Hope this helps. See more info here: https://docs.python.org/3/library/textwrap.html

Upvotes: 2

Related Questions