在python中使用{}格式无法正确显示输出?
我有一个字典列表,我正试图使用python中的format选项在控制台上打印它的输出。 下面的程序在按照下面提到的所需格式打印输出时出错。我遇到的两个错误是“索引超出元组的范围”,精度不是整数格式。解决这些错误并显示以下输出的方法 节目 我需要上面程序的输出如下所示 期望输出:在python中使用{}格式无法正确显示输出?,python,Python,我有一个字典列表,我正试图使用python中的format选项在控制台上打印它的输出。 下面的程序在按照下面提到的所需格式打印输出时出错。我遇到的两个错误是“索引超出元组的范围”,精度不是整数格式。解决这些错误并显示以下输出的方法 节目 我需要上面程序的输出如下所示 期望输出: NAME ID ipaddr/nm neighour proto status enabled ipv6enable ------ --- ------
NAME ID ipaddr/nm neighour proto status enabled ipv6enable
------ --- ------------ -------- ----- ------ ------- ----------
stevekar 3 10.1.2.3/24 17.16.1.1 dhcp up True False
john 4 20.1.1.1/24 192.168.1.1 static up True False
192.169.2.6
daren 6 156.1.1.1/30 19.16.1.2 dhcp up True False
错误:
修改如下:
fmt = "{} {} {}/{} {} {} {} {} {}"
print fmt.format("NAME", "ID", "ipaddr", "nm", "neighour", "proto", "status", "enabled", "ipv6enable")
print fmt.format( '---------', '---', '----------------', '---', '----------------', '------', '-----', '-----', '--------')
输出显示为
NAME ID ipaddr/nm neighour proto status enabled ipv6enable
--------- --- ----------------/--- ---------------- ------ ----- ----- --------
stevekar 3 10.1.2.3/24 17.16.1.1 dhcp up True False
john 4 20.1.1.1/24 192.168.1.1 192.169.2.6 static up True False
daren 6 156.1.1.1/30 19.16.1.2 dhcp up True False
我已尝试使用以下工具将其正确对齐:
fmt = "{:10.10} {:7.7} {:13.13}/{} {:13.30} {:9} {:9} {:9} {:}
错误为:
NAME ID ipaddr /nm neighour proto status enabled ipv6enable
--------- --- -------------/--- ---------------- ------ ----- ----- --------
Traceback (most recent call last):
File "json_format.py", line 19, in <module>
data_dict['enabled'], data_dict['ipv6enable'])
ValueError: Precision not allowed in integer format specifier
NAME ID ipaddr/nm neighour proto status enabled ipv6enable
--------- --- -------------/--- ---------------- ------ ----- ----- --------
回溯(最近一次呼叫最后一次):
文件“json_format.py”,第19行,在
数据目录['enabled'],数据目录['ipv6enable'])
ValueError:整数格式说明符中不允许精度
在调用格式时只需使用逗号(
:)
例如:
fmt.format('NAME','ID',…)
感谢您对元组错误的回答。但是,当我试图正确格式化输出时,ValueError:Precision不允许在整数格式说明符中使用(如上图所示)。您能帮我一下吗?有什么错误吗。
NAME ID ipaddr/nm neighour proto status enabled ipv6enable
--------- --- ----------------/--- ---------------- ------ ----- ----- --------
stevekar 3 10.1.2.3/24 17.16.1.1 dhcp up True False
john 4 20.1.1.1/24 192.168.1.1 192.169.2.6 static up True False
daren 6 156.1.1.1/30 19.16.1.2 dhcp up True False
fmt = "{:10.10} {:7.7} {:13.13}/{} {:13.30} {:9} {:9} {:9} {:}
NAME ID ipaddr /nm neighour proto status enabled ipv6enable
--------- --- -------------/--- ---------------- ------ ----- ----- --------
Traceback (most recent call last):
File "json_format.py", line 19, in <module>
data_dict['enabled'], data_dict['ipv6enable'])
ValueError: Precision not allowed in integer format specifier