Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing with indentation in python

is there a way to print the following,

print user + ":\t\t" + message 

so that lengthy messages that are wider than the length of the terminal always wraps (starts from the same position) ? so for example this

Username:              LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT 

should become

Username:              LEFTLEFTLEFTLEFTLEFTLEFTLEFT                        RIGHTRIGHTRIGHT 
like image 573
Algorithmatic Avatar asked Sep 12 '13 06:09

Algorithmatic


People also ask

How do I turn on pretty printing in Python?

To use pprint, begin by importing the library at the top of your Python file. From here you can either use the . pprint() method or instantiate your own pprint object with PrettyPrinter() .

How do I print indentation in Python?

In Python, four whitespaces are normally used for indentation; however, most IDEs do this automatically. This is the same case with functions where indentation is used to mark the beginning of the function's body.

How do you indent text in Python?

You can indent the lines in a string by just padding each one with proper number of pad characters. This can easily be done by using the textwrap. indent() function which was added to the module in Python 3.3.


Video Answer


1 Answers

I think what you're looking for here is the textwrap module:

user = "Username" prefix = user + ": " preferredWidth = 70 wrapper = textwrap.TextWrapper(initial_indent=prefix, width=preferredWidth,                                subsequent_indent=' '*len(prefix)) message = "LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT " * 3 print wrapper.fill(message) 

This prints:

Username: LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT           LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT           LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT 

If you actually want to use tabs in the indent, that's a little trickier, because you have to first tab-expand the initial_indent to figure out the correct subsequent_indent to use. And, because your prefix actually ends with two tabs, it's even more complicated. Here's the simplest I've come up with:

user = "Username" prefix = user + ":\t\t" expanded_indent = textwrap.fill(prefix+'$', replace_whitespace=False)[:-1] subsequent_indent = ' ' * len(expanded_indent) wrapper = textwrap.TextWrapper(initial_indent=prefix,                                subsequent_indent=subsequent_indent) message = "LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT " * 3 print wrapper.fill(message) 

If you do this repeatedly, you will probably want to wrap that mess up in a function.

like image 176
abarnert Avatar answered Oct 07 '22 13:10

abarnert