Skip to content
Advertisement

Python tabulate: how to achieve auto lining in tabulate?

from tabulate import tabulate
table_header = ['Options', 'Explain','Impact']
table_data = []
for i in self.add_list:
    table_data.append( (somethingtoprint) )
pfile.write(tabulate(table_data, headers=table_header, tablefmt='grid'))

Here , when somethingtoprint is very long string, the output format is corrupted. Is there any way to use tabulate more pretty?

Updated: I mean the table content is so long that it will exceed the screen width, then the display can be messed up.

like

id name

123 “zzzzzzzzzzzzzzzzadsas daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa”

Thank you

Advertisement

Answer

I can’t comment. What does this “very long string” look like? I used this code below and it worked fine for me. My very long string was 2,970 characters long.

table = [["Sun"*990 ,696000,1989100000],["Earth",6371,5973.6],
          ["Moon",1737,73.5],["Mars",3390,641.85]]
print(tabulate(table))

Addressing comments. Yes, it is that way because there are no line returns in the string. I’m guessing the author of the package didn’t want to arbitrarily add line returns. You can insert your own line returns and tabulate will handle them. The output is dependent on font size and screen width. If the length of the line surpasses your screen width then it wraps. I think that’s what you mean by it looks bad. You can output to a file and view it (make sure to turn off any line wrap features).

Here is an example of how to do that.

from tabulate import tabulate
from pathlib import Path

table = [["Sun"*990,696000,1989100000],["Earth",6371,5973.6],
          ["Moon",1737,73.5],["Mars",3390,641.85]]

file_output = Path('test.txt')
file_output.write_text(tabulate(table))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement