在Python中打印标题信息以提高可读性

2024-05-06 17:43:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我学习了下面的代码,它通过从我的列表.txt“文件,现在我正在寻找一种方法来打印输出,在每个输出的顶部都有一个非常人性化的from Like列标题,然后是名称(在下面)。。在

有没有办法在打印时设置列宽。。。在

#!/usr/bin/python

import sys
import socket
with open("mylabList.txt", 'r') as f:

  for host in f:
        print("{0[0]}\t{0[2][0]}".format(socket.gethostbyname_ex(host.rstrip())))

电流输出如下:

^{pr2}$

预期产量为:

Server Name     IP ADDRESS
===================================
mylab1.example.com      172.10.1.1
mylab2.example.com      172.10.1.2
mylab3.example.com      172.10.1.3
mylab4.example.com      122.10.1.4

只是个便条。。在我的输出中,Srever Name的lenghth最长可达30个字符。在


Tags: 文件方法代码namefromimporttxtcom
1条回答
网友
1楼 · 发布于 2024-05-06 17:43:18

你可以用ljust和rjust

http://www.tutorialspoint.com/python/string_ljust.htmhttp://www.tutorialspoint.com/python/string_rjust.htm

print("A String".ljust(30, " ") + "Another String")

结果

^{pr2}$

这是一种可能的方法:

#!/usr/bin/python

import sys
import socket
print("Server Name".ljust(30, " ") + "IP ADRESS")
print("="*39)
with open("mylabList.txt", 'r') as f:
    for host in f:
        print("{0[0]}\t{0[2][0]}".format(socket.gethostbyname_ex(host.rstrip())))

相关问题 更多 >