如何将变量值作为参数传递给格式函数

时间:2020-06-11 13:51:33

标签: python python-3.x string

我试图创建一个format逻辑,在这里我需要将参数从变量传递给format函数,而不是对其进行编码。

 key = "test"
 inpText = "replace {test} with value"
 inpText = inpText.format(key = "done")

2 个答案:

答案 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
相关问题