Python:替换未知数量的字符串变量

2024-04-16 12:28:10 发布

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

我需要定义一个函数来遍历一个字符串并替换所有替换字段,而不知道会有多少替换字段。我知道替换字段将以特定方式命名。例如,如果我知道所有字段都将命名为“name”和“position”:

Test1 = "I think {name} should be our {position}. Only {name} is experienced. Who else could be a {position}?"
Test2 = "{name} is the only qualified person to be our {position}."

我需要一个函数,它可以以相同的方式处理这两个问题,输出如下:

^{pr2}$

我觉得这应该很简单,但我的头脑似乎无法越过倍数和未知量。在


Tags: 函数字符串nameonly定义is方式position
3条回答
def ModString(s, name_replacement, position_replacement):
    return s.replace("{name}",name_replacement).replace("{position}", position_replacement)

然后:

^{pr2}$

或者您可以使用.format(),这是推荐的

def ModString(s, name_replacement, position_replacement):
    return s.format(name=name_replacement, position=position_replacement)

bphi是对的,使用字符串格式 e、 g

test1 = "I think {name} should be our {position}. Only {name} is experienced. Who else could be a {position}?"
test1.format(name="Bob", position="top cat")
> 'I think Bob should be our top cat. Only Bob is experienced. Who else could be a top cat?'

在str.格式()我脑子里也有这个念头。在

相关问题 更多 >