mark12345
mark12345

Reputation: 293

Python PrettyTable add ljust

Can anyone help me. I'm struggling for an hours already.

I have this table:

+-------------------------------------------------+
|                      TRACKS                     |
+---+----------+----------+----------+------------+
| # | Bitrate  | Size     | Name     | Resolution |
+---+----------+----------+----------+------------+
| 1 | 85 kb/s  | 3565734  | filename | 608x342    |
| 2 | 104 kb/s | 4313093  | filename | 768x432    |
| 3 | 149 kb/s | 6012783  | filename | 768x432    |
| 4 | 213 kb/s | 8496984  | filename | 960x540    |
| 5 | 280 kb/s | 11034661 | filename | 1280x720   |
| 6 | 350 kb/s | 13729229 | filename | 1280x720   |
| 7 | 564 kb/s | 21957280 | filename | 1920x1080  |
| 8 | 667 kb/s | 25902984 | filename | 1920x1080  |
+---+----------+----------+----------+------------+

I wanted to add ljust(7) so it will be align with my logger message. like below.

For example:

INFO: Some texts here before the table
      +-------------------------------------------------+
      |                      TRACKS                     |
      +---+----------+----------+----------+------------+
      | # | Bitrate  | Size     | Name     | Resolution |
      +---+----------+----------+----------+------------+
      | 1 | 85 kb/s  | 3565734  | filename | 608x342    |
      | 2 | 104 kb/s | 4313093  | filename | 768x432    |
      | 3 | 149 kb/s | 6012783  | filename | 768x432    |
      | 4 | 213 kb/s | 8496984  | filename | 960x540    |
      | 5 | 280 kb/s | 11034661 | filename | 1280x720   |
      | 6 | 350 kb/s | 13729229 | filename | 1280x720   |
      | 7 | 564 kb/s | 21957280 | filename | 1920x1080  |
      | 8 | 667 kb/s | 25902984 | filename | 1920x1080  |
      +---+----------+----------+----------+------------+

my current code:

t = PrettyTable()
t.title = 'TRACKS'
t.field_names = ['#', 'Bitrate', 'Size','Name', 'Resolution']
for v in test:
    t.add_row([v['num'], v['bitrate'], v['size'], v['profile'], v['resolution']])
t.align = 'l'
print(t)

Upvotes: 0

Views: 318

Answers (1)

BoarGules
BoarGules

Reputation: 16942

You want to add padding on the left of the table. But PrettyTable does not offer such an option, so you need to do it yourself. Split the string that it produces into lines, and print those lines one by one with spaces on the left:

for row in t.get_string().split("\n"):
    print (" "*5,row)

Upvotes: 1

Related Questions