需要在单个lin中用不同的值替换ip地址

2024-10-08 19:31:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要替换ip ospf db area <IP4ADDR> ex <IP4ADDR> rtr <IP4ADDR>

ip ospf db area 0.0.0.1 ex 0.0.0.0 rtr 222.0.0.1。你知道吗

我试过了,但不符合要求。你知道吗

>>> str = "ip ospf db area <IP4ADDR> ex <IP4ADDR> rtr <IP4ADDR>"
>>> newstr = str.replace("<IP4ADDR>","0.0.0.1")
>>> newstr
'ip ospf db area 0.0.0.1 ex 0.0.0.1 rtr 0.0.0.1'

为了得到期望的结果,所有3个IP地址都将被替换为不同的值。如果python中有任何可用的功能,有人能帮我吗?你知道吗


Tags: 功能ipdbareareplaceexstr符合要求
2条回答

您可以传递一个可选参数count。根据Python文档:

...If the optional argument count is given, only the first count occurrences are replaced.

因此,您可以进行链式调用(这将起作用,因为replace()返回修改后的字符串):

new_str = some_str.replace("<IP4ADDR>", "0.0.0.1", 1)\
    .replace("<IP4ADDR>", "0.0.0.0", 1)\
    .replace("<IP4ADDR>", "222.0.0.1", 1)

注意:这与执行以下操作几乎相同:

new_str = some_str.replace("<IP4ADDR>", "0.0.0.1", 1)
new_str = new_str.replace("<IP4ADDR>", "0.0.0.0", 1)
new_str = new_str.replace("<IP4ADDR>", "222.0.0.1", 1)

您可以向re.sub传递一个函数,该函数每次返回不同的替换字符串。例如:

import re

s = "ip opf db area <IP4ADDR> ex <IP4ADDR> rtr <IP4ADDR>"
replacements = iter(['0.0.0.1', '0.0.0.0', '222.0.0.1'])
newstr = re.sub(r'<IP4ADDR>', lambda m: next(replacements), s)

相关问题 更多 >

    热门问题