pythonprettytable

How to access a cell ignoring the Title?


I;m trying to access an element of a cell from pretty table. When I tried that the title of the pretty table also comes as part of the output. is there a way to ignore it?

from prettytable import PrettyTable

table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.title = 'TESTING'
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])


for row in table:
    row.border = False
    row.header = False
    print(row.get_string(fields = ['Column 1']).strip())

output is as follows:

| TESTING |
  A
| TESTING |
  F
| TESTING |
  B

But i want only the fields particularly the cell values and i dont want the title. can someone kindly help.

i tried searching throught the documentation of prettytable but could not find it online.


Solution

  • It doesn't look like get_string provides a straight forward API to achieve that, but we can cheat by using \r as the temporary title and use NONE for vrules:

    from prettytable import PrettyTable, NONE
    ...
    for row in table:
        print(row.get_string(fields=['Column 1'],
                             border=False,
                             header=False,
                             title='\r',
                             vrules=NONE).strip())
    

    Or we can use a lower-level API:

    for row in table.rows:
        print(row[0])
    

    Both will output

    A
    F
    B
    

    To get a specific cell's value you can use start and stop arguments which are zero-based and are inclusive-exclusive (like Python's range):

    print(table.get_string(fields=['Column 1'],
                           border=False,
                           header=False,
                           title='\r',
                           vrules=NONE,
                           start=1,
                           end=2).strip())
    

    will output

    F