我需要定义一个函数来通过字符串并替换所有替换字段,而不知道会有多少。我确实知道替换字段将被命名为特定方式。例如,如果我知道所有字段都将被命名为“名称”和“位置”:
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}."
我需要一个函数,以相同的方式处理这两个函数,并输出如下:
>>Test1 = ModString(Test1)
>>Test2 = ModString(Test2)
>>Test1
>>'I think Mary should be our boss. Only Mary is experienced. Who else could be a boss?'
>>Test2
>>'Mary is the only qualified person to be our boss.'
我觉得这应该很简单,但是我的头脑似乎无法超越倍数和未知数。
答案 0 :(得分:0)
str.format()我对此深有感触。
答案 1 :(得分:0)
bphi是正确的,使用字符串格式 例如
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?'
答案 2 :(得分:0)
for day in array:
price = price - (price * .1)
print(day, price)
然后:
def ModString(s, name_replacement, position_replacement):
return s.replace("{name}",name_replacement).replace("{position}", position_replacement)
或者您可以只使用Test1 = ModString(Test1, "Mary", "boss")
Test2 = ModString(Test2, "Mary", "boss")
,推荐
.format()
答案 3 :(得分:0)
您必须使用replace()方法,例如,在这里阅读:https://www.tutorialspoint.com/python/string_replace.htm
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}."
def ModString(str, name, position):
str = str.replace("{name}", name)
str = str.replace("{position}", position)
return str
Test1 = replaceWord(Test1, "Mary", "boss")
Test2 = replaceWord(Test2, "Mary", "boss")