如何在Python中以有序格式打印出来

时间:2017-12-26 00:45:52

标签: python printing

Print Statement ---输出图像

第二行的长度增加,因为它有更多的字符,我如何保持一个恒定的空间,我有这样的东西在for循环中打印

for i in range(0,len(arp_table)):
    print(arp_table[i].interface_name+"         "+arp_table[i].ip_address+"

1 个答案:

答案 0 :(得分:0)

您可以使用formatting specification字符串。

您没有给出完整的情况示例,因此我必须假设您的数据结构:

class Arp_entry:
    def __init__(self, interface_name, ip_address, mac):
        self.interface_name = interface_name
        self.ip_address = ip_address
        self.mac = mac

arp_table = [
    Arp_entry("em1.0", "128.0.0.16", "00:0c:29:38:fa:60"),
    Arp_entry("ge-0/0/0.0", "172.17.1.2", "00:0c:29:74:6b:a6"),
    Arp_entry("ge-0/0/1.0", "172.17.3.2", "00:0c:29:74:6b:b0"),
    Arp_entry("fxp0.0", "192.168.0.16", "b8:27:eb:45:b8:30"),
    Arp_entry("fxp0.0", "192.168.0.22", "4c:32:75:96:72:eb"),
    Arp_entry("fxp0.0", "192.168.0.23", "00:0c:29:af:f0:a5"),
    Arp_entry("fxp0.0", "192.168.0.24", "00:0c:29:cc:a8:c3")
    ]

formatting_string = "{0:<25}{1:<25}{2:<30}"

print(formatting_string.format("INTF", "IP_ADDRESS", "MAC"))
print(formatting_string.format("----", "----------", "---"))

for current_entry in arp_table:
    print(formatting_string.format(current_entry.interface_name,
                                   current_entry.ip_address,
                                   current_entry.mac))