使用 print 命令在表中简化 Python 输出

标签 python linux scripting formatting

在Python脚本中,我正在读取命令输出并将它们放入循环中以提取特定列,我正在尝试格式化输出,使其看起来不错,但如果结果中字符较多,则它会有点困惑。我该如何让它们看起来好看?

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

输出:

[root@tux 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

我想要像下面这样的输出

[root@tux 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

最佳答案

一种方法是使用字符串格式。根据您的样本,可能是这样的:

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

正如@twalberg 已经评论的那样,您可以阅读更多内容 here

关于使用 print 命令在表中简化 Python 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29851644/

相关文章:

python - Robot FrameWork::在关键字结束前返回一个值

python - 在 PyQt4 中向 MPL 图添加工具栏

上次添加的 Linux 脚本

linux -/proc/<pid>status SigIGN 字段

java - 没有特殊字符的字符串比较

python - 如何让 if 语句接受三个参数中的任何一个而不在 Python 中全部为真

python - 为什么变量在更改其因变量后不更新?

c++ - "standard output stream"和 "standard output device"有什么区别?

git post-commit hook - 提交文件的脚本

linux - 检查linux版本的更好方法?