Tag Archives: Python

Python textwrap – Wrap your text to terminal size

Following the last post “Python textwrap – Fix Your Multiline Strings Indentations” – where we learned how to fix the indentation caused by the python indentation standards.
In this post I want to show you how to create a wrap to your text that support multiline and smart indent.

This might sound old to you but the original terminal (standard) was and still is 80 characters width. Long ago when I’ve started working on CLI applications and scripts my boss asked me to see the “usage/help” of one of them, then he looked at me and said – This is not 80 characters width! This is not terminal standard – Fix this!”
Back then I’ve just trimmed my lined and fix this.
More then 500 scripts later and 4 languages into the future I’ve looked at this and thought – There might be a better way to do this.
And there in python was the answer.

Let’s start with example:

>>> import textwrap
>>> x = "This is the first line of the text - This line is far more then then 80 characters and will need to be wraped to 80 characters width"
>>> print x
This is the first line of the text - This line is far more then then 80 characters and will need to be wraped to 80 characters width
>>> #Lets wrap it to 80 characters
>>> print textwrap.fill(x, width=80)
This is the first line of the text - This line is far more then then 80
characters and will need to be wraped to 80 characters width
SyntaxError: invalid syntax
>>> #See that the words won't break (Unless this is a long word)

Now let’s try that with a multiline string:

>>> x = '''
This is a mltiline string, now this is the first line and it will be more then 50 characters width for the example.
Now we create a new line with more then 50 width as the second line'''
>>> print textwrap.fill(x, width=50)
 This is a mltiline string, now this is the first
line and it will be more then 50 characters width
for the example. Now we create a new line with
more then 50 width as the second line
>>>

As you can see the second line was integrated into the first line instead of being on it’s own line – This is one of the problems with textwrap – it works only on a single line. Continue reading Python textwrap – Wrap your text to terminal size

Python textwrap – Fix Your Multiline Strings Indentation

I’ve been writing a lot in python the last couple of months and most of my code is for a CLI oriented environment (Mostly Linux/Unix shell).

One of the most important things when you create CLI is the help and usage string – Mostly because other people will try to use it – But lets face it, that script you’ve written a month ago? You’ve probably completely forgotten how it works.

So writing help or usage usually means that you work with an external file or multiline string. Continue reading Python textwrap – Fix Your Multiline Strings Indentation