我试图创建一个format
逻辑,在这里我需要将参数从变量传递给format
函数,而不是对其进行编码。
key = "test"
inpText = "replace {test} with value"
inpText = inpText.format(key = "done")
答案 0 :(得分:0)
我认为您想为此使用带有f字符串的函数?
def fill_input(key):
return f"replace {key} with value"
>>> print(fill_input("test"))
"replace test with value"
>>> print(fill_input("done"))
"replace done with value"
答案 1 :(得分:0)
您的问题是key
将被寻找作为占位符。为format
提供额外的占位符不会引起错误,但test
占位符将丢失。要将key
中的字符串作为占位符传递,您可以使用关键字通过字典将其解压缩:
key = "test"
inpText = "replace {test} with value"
replacements = {key: "done"}
inpText = inpText.format(**replacements)
print(inpText)
将打印:
replace done with value