1

Let's say I have the following file.txt

$ cat file.txt
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

If I try reading the file like this:

with open('file.txt') as fp:
    lines = fp.readlines()

And then I try to display each line using the gtk2.0 textbuffer (similar to print):

for eachline in lines:
    if idx == 0:
        self.textbuffer.delete(start, end)
        end = self.textbuffer.get_end_iter()
        self.textbuffer.set_text(eachline)
    else:
        self.textbuffer.insert(end, eachline)
        end = self.textbuffer.get_end_iter()

I get the following output:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide |  1295 |  1158259 |      600.5      |
| Brisbane  | 5905  |  1857594   |      1146.4     |
| Darwin   | 112  |   120900   |      1714.7     |
| Hobart   | 1357 |   205556   |      619.5      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne  | 1566 |  3806092   |      646.9      |
| Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

Any suggesstion how to make it look prettier (like the first table) ?

Thanks in advance!

Matthias Wiehl
  • 1,799
  • 16
  • 22
Rodrigo P
  • 39
  • 4

1 Answers1

2

you might want to format your strings like the following:

Python: Format output string, right alignment the with in the output like

for align, text in zip('<^>', ['left', 'center', 'right']): 
    '{0:{fill}{align}16}'.format(text, fill=align, align=align)

in the output, you can specify the with (or get that based on the length of your inputs).

I have not worked with gtk2.0 myself but perhaps it will help https://docs.python.org/3/library/string.html#formatstrings

FireByTrial
  • 21
  • 1
  • 4