【问题标题】:Python for loop, prints on multiple linesPython for循环,多行打印
【发布时间】:2021-08-17 14:10:14
【问题描述】:

首先,我是一名网络工程师并完成了 Python 新手,我知道基础知识,我可以阅读一些内容,但很难将它们组合在一起。

我写了一个非常基本的for循环脚本:

    ip_list = open('/home/daryll/scripts/ip_list')
    for ip in ip_list:
        print ("set security address-book global address", ip, ip + "/32")

我期待这个回来:

set security address-book global address 192.168.10.1 192.168.10.1/32  
set security address-book global address 192.168.10.2 192.168.10.2/32  
set security address-book global address 192.168.10.3 192.168.10.3/32

但是我得到了这个:

set security address-book global address 192.168.10.1
 192.168.10.1
/32
set security address-book global address 192.168.10.2
 192.168.10.2
/32
set security address-book global address 192.168.10.3
 192.168.10.3
/32

我相信这对你们来说是显而易见的,但对我来说不是,我会很感激我的代码

要添加到此,我如何添加多个不同的行,例如

        commands = ( 
    "set interfaces", ip, "family ethernet-switching port-mode trunk"
    "set interfaces", ip, "family ethernet-switching vlan members vlan1"
    "set interfaces", ip, "family ethernet-switching native-vlan-id vlan2"
    )

我不会显示输出,因为它非常混乱,但是当我这样做时,我将所有内容都放在 1 行我怎么能得到

    set interfaces 192.168.10.1 family ethernet-switching port-mode trunk
    set interfaces 192.168.10.1 family ethernet-switching vlan members vlan1
    set interfaces 192.168.10.1 family ethernet-switching native-vlan-id vlan2

最后我不知道这是否是我问这个问题的方式

谢谢

【问题讨论】:

    标签: python-3.x for-loop


    【解决方案1】:

    遍历文件中的行将在每一行的末尾留下一个换行符 (\n),最后一行除外。要删除它,只需使用 .strip() 删除换行符的每一行。

        ip_list = open('/home/daryll/scripts/ip_list')
        for ip in ip_list:
            ip = ip.strip()
            print("set security address-book global address", ip, ip + "/32")
    

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 2018-02-04
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      相关资源
      最近更新 更多