pythonprettytable

How to get the value of a cell when using prettytable


Is it possible to get the value of a specific cell when using prettytable?

I have the following code to iterate through all rows of a simple table.

from prettytable import PrettyTable

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

for row in table:
    print(row)

This example prints the following 3 tables:

+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    A     |    B     |    C     |
+----------+----------+----------+
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    F     |    O     |    O     |
+----------+----------+----------+
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    B     |    A     |    R     |
+----------+----------+----------+

How is it possible to get only the value of Column 1, Column 2 or Column 3 of a row?


Solution

  • It looks like what you want to do is get a subset of the data, from the documentation here, try:

    from prettytable import PrettyTable
    
    table = PrettyTable(["Column 1", "Column 2", "Column 3"])
    table.add_row(["A", "B", "C"])
    table.add_row(["F", "O", "O"])
    table.add_row(["B", "A", "R"])
    
    for row in table:
        print row.get_string(fields=["Column 1"]) # Column 1
    

    Edit: It looks like you don't want the headers or border, just the value, in which case, this should work:

    from prettytable import PrettyTable
    
    table = PrettyTable(["Column 1", "Column 2", "Column 3"])
    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() # Column 1