Python-如何打印列表项/条目的文本而不是其值?

时间:2018-11-22 16:56:35

标签: python list printing

例如

r2 = '192.168.122.72'
r3 = '192.168.122.73'
hostnames = [r2,r3]
#commands = ['term len 0','show run']
for r in hostnames:
    print (r)
    print (hostnames)
    print str(r)

此输出是...

192.168.122.72
['192.168.122.72', '192.168.122.73']
192.168.122.72
192.168.122.73
['192.168.122.72', '192.168.122.73']
192.168.122.73

我实际上想看到一个输出,该输出将说出项目的文字文本,而不是它的值,所以我实际上想看到它。……

r2
r3

最终,要创建一个文件,该文件是路由器的名称,而不是其IP。

提前谢谢!

1 个答案:

答案 0 :(得分:2)

这是不可能的。您必须为此使用字典。

示例:

r2 = '192.168.122.72'
r3 = '192.168.122.73'
hostnames = {'r2':r2,'r3':r3}
#commands = ['term len 0','show run']
for r in hostnames:
    print (r)
    print (hostnames)
    print str(r)