pythonprettytable

How to make a table with PrettyTable that only has one horizontal line under the title?


I want a very minimal table which I attempted as follows:

from prettytable import PrettyTable, HEADER, FRAME, ALL, NONE

output = PrettyTable(align='l', header=False)
output.title = 'My Table'
output.border = False
output.hrules = HEADER
output.add_row([1, 2, 3])
output.add_row([4, 5, 6])
output.add_row([7, 8, 9])
print(output)

Output:

  My Table  
 1   2   3  
 4   5   6  
 7   8   9  

Desired output:

  My Table  
-----------
 1   2   3  
 4   5   6  
 7   8   9  

Solution

  • You can achieve that style using the following

    from prettytable import PrettyTable, FRAME, NONE
    
    output = PrettyTable(align='l', header=False)
    output.title = 'My Table'
    output.hrules = FRAME # horizontal border only at start and end
    output.vrules = NONE  # no vertical border
    
    output.add_row([1, 2, 3])
    output.add_row([4, 5, 6])
    output.add_row([7, 8, 9])
    
    # remove end border
    formatted = "\n".join(str(output).splitlines()[:-1])
    
    print(formatted)
    

    From what I could tell from the library source there is no way to get the style you want without the splitlines/join bit at the end to remove the bottom border line.