Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading