当前位置:首页>python>从零开始学python-字符串格式化(占位符)使用示例

从零开始学python-字符串格式化(占位符)使用示例

  • 2026-09-04 02:12:55
从零开始学python-字符串格式化(占位符)使用示例

Hi~新朋友,记得点上面蓝字(网虫root)关注哟~

前言:

在网络配置中,批量生成有规律的配置项时,手动逐条编写既繁琐又低效。利用 for 循环结合字符串格式化(占位符)可以自动生成这类配置,大幅节省时间并减少出错。

示例1:使用for + %格式化方式,生成ubuntu16.04单网卡绑定多ip的配置

📖脚本如下:

j=2k=0for i in range(3):    print("auto eth0:%d""\n"                               "iface eth0:%d inet static""\n"          "address 192.168.121.%d""\n"          "netmask 255.255.255.0""\n"%(k,k,j))    k+=1    j+=1

📝生成内容:

auto eth0:0iface eth0:0 inet staticaddress 192.168.121.2netmask 255.255.255.0auto eth0:1iface eth0:1 inet staticaddress 192.168.121.3netmask 255.255.255.0auto eth0:2iface eth0:2 inet staticaddress 192.168.121.4netmask 255.255.255.0

示例2:使用for + format() 方法,生成给交换机端口添加端口描述并加入eth-trunk的配置

🔍脚本如下:

k=1j=1for i in range(3):	print("interface  GE 1/0/{}""\n"          "des DC-POD1-OceanStor9540-{}-mgmt_port1""\n"		  "eth-trunk  {}""\n"          "#""\n"          "interface  GE 2/0/{}""\n"          "des DC-POD1-OceanStor9540-{}-mgmt_port2""\n"		  "eth-trunk  {}""\n"          "#""\n".format(k,j,k,k,j,k))	k += 1	j += 1

🌿生成内容:

interface  GE 1/0/1des DC-POD1-OceanStor9540-1-mgmt_port1eth-trunk  1#interface  GE 2/0/1des DC-POD1-OceanStor9540-1-mgmt_port2eth-trunk  1#interface  GE 1/0/2des DC-POD1-OceanStor9540-2-mgmt_port1eth-trunk  2#interface  GE 2/0/2des DC-POD1-OceanStor9540-2-mgmt_port2eth-trunk  2#interface  GE 1/0/3des DC-POD1-OceanStor9540-3-mgmt_port1eth-trunk  3#interface  GE 2/0/3des DC-POD1-OceanStor9540-3-mgmt_port2eth-trunk  3#

【微语】迷茫是因为想得太多,书读得太少,路走得太短。

网虫root

期待你的

分享

点赞

在看

最新文章

随机文章