假设我有以下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 |
+-----------+------+------------+-----------------+
如果我尝试这样读取文件:
with open('file.txt') as fp:
lines = fp.readlines()
然后我尝试使用gtk2.0文本缓冲区显示每一行(类似于打印):
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()
我得到以下输出:
+-----------+------+------------+-----------------+
| 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 |
+-----------+------+------------+-----------------+
任何建议如何使它看起来更漂亮(如第一张桌子)?
谢谢!
答案 0 :(得分:2)
您可能想要像下面这样格式化字符串:
Python: Format output string, right alignment 输出中的
for align, text in zip('<^>', ['left', 'center', 'right']):
'{0:{fill}{align}16}'.format(text, fill=align, align=align)
在输出中,您可以指定with(或根据输入的长度获取)。
我自己还没有使用过gtk2.0,但也许可以帮助https://docs.python.org/3/library/string.html#formatstrings