[英]Print Header Information for Human Readability in Python
I learned and code below which gives the Hostnames and Its IP address by the reading the hostname from the "mylabList.txt" file, Now i am looking the way to print the output in a pretty Human readable from Like Column header at the top of each and then the name (Below that).. 我从下面的代码中学到了代码,它通过从“ mylabList.txt”文件中读取主机名来提供主机名及其IP地址,现在我正在寻找以类似“人类易读”的方式从顶部的“列”标题打印输出的方式每个,然后是名称(在其下)。
Is there way to set width between columns while printing... 打印时是否可以设置列之间的宽度...
#!/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())))
Current output is Like: 当前输出为:
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
Expected Output is: 预期输出为:
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
Just a note.. in my output Srever Name's lenghth is upto 30 Char long. 请注意,在我的输出中,Srever Name的长度最长为30个字符。
You could use ljust and rjust 你可以用正义和正义
http://www.tutorialspoint.com/python/string_ljust.htm http://www.tutorialspoint.com/python/string_rjust.htm http://www.tutorialspoint.com/python/string_ljust.htm http://www.tutorialspoint.com/python/string_rjust.htm
print("A String".ljust(30, " ") + "Another String")
results in 结果是
A String Another String
This is a possible way to do the trick: 这是解决问题的一种可能方法:
#!/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())))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.