0
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

shenmufeng
  • 67
  • 1
  • 7
  • Can you share what the output would actually look like? Or at least that of a **[mcve]**. – AMC Mar 14 '20 at 04:11

2 Answers2

1

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))
Stuart
  • 465
  • 3
  • 6
  • Thanks Stuart! I mean to exceed the screen width, and it's display is just messed up. @Stuart – shenmufeng Mar 14 '20 at 03:14
  • @shenmufeng I edited the answer based on your comment. – Stuart Mar 14 '20 at 03:25
  • @shenmufeng to clarify, I'm not aware of a terminal that allows you to disable word wrapping. Best bet is to output to a text file and disable word wrapping in the text file so you can scroll horizontally. Alternatively, input your own new line characters (`\n`) then print the table. – Stuart Mar 15 '20 at 01:26
0

Workaround: Pipe into a pager and disable wrapping, e.g. less -S or most

Raphael
  • 9,779
  • 5
  • 63
  • 94