Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping text during print Python

I am printing a few variables in a row. One of the variables is a very long string that I want to wrap the text (currently it's printing half a word at the end of a line if it has to) so I would like the whole word to start on the next line if all of it will not fit o nthe previous line.

For example:

print(item.name,":",item.description,"\n\nValue :",item.value)

I need item.decription to wrap. I can wrap the whole lot if that helpds, but I don't want to end up with characters left on the screen fro mthe wrap operation in any case. I tried:

import textwrap
print(item.name,":",textwrap.wrap(item.description),"\n\nValue :",item.value)

but this doesn't work. The words don't wrap and I get square bracket characters and random commas instead in the output. How should I accomplish what should be a pretty simple wrap?

like image 679
Simkill Avatar asked Jun 07 '13 09:06

Simkill


1 Answers

Use textwrap.fill() instead, it joins the lines with newline characters:

print(item.name, ":", textwrap.fill(item.description), "\n\nValue :", item.value)

textwrap.wrap() returns a list of wrapped lines.

like image 191
Martijn Pieters Avatar answered Sep 27 '22 17:09

Martijn Pieters