2015-04-24 19 views
0

在Python腳本中,我正在閱讀命令輸出並將它們放入循環中以提取特定列,我試圖格式化輸出以使其看起來不錯,但如果結果中的字符更少,它就會變得雜亂無章。我如何讓他們看起來很好?Python輸出在打印命令表中精簡

for i in data: 
      print i[2], '|', i[12], '\t|', i[9], '\t\t\t|', i[24].split('@')[-1] 

輸出:

[[email protected] work]# ./foo.py 
2015-04-24 10:26:44 | RINGING | 17654742161     | 
2015-04-24 10:26:44 | RINGING | 00100017654742161      | 
2015-04-24 10:13:52 | ACTIVE | 18146252950     | 72.xx.xx.120 
2015-04-24 10:24:25 | ACTIVE | 17323576331     | 72.xx.xx.120 

我想出來讓像下面

[[email protected] work]# ./foo.py 
    2015-04-24 10:26:44 | RINGING | 17654742161     | 
    2015-04-24 10:26:44 | RINGING | 00100017654742161    | 
    2015-04-24 10:13:52 | ACTIVE | 18146252950     | 72.xx.xx.120 
    2015-04-24 10:24:25 | ACTIVE | 17323576331     | 72.xx.xx.120 
+0

看一看[這裏](https://docs.python.org /2/library/string.html#formatspec)和[here](https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-的xrange) – twalberg

回答

0

一種方法是使用字符串格式化。根據您的樣品,它可以是這樣的:

for i in data: 
    params = [i[2], i[12], i[9], i[24].split('@')[-1]] 
    print '{:20s} | {:10s} | {:20s} | {:16s}'.format(*params) 

正如已經@twalberg評論,你可以閱讀更多here