Printing with indentation in python

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)