Search code examples
pythonpython-3.xstring-formatting

In string formatting can I replace only one argument at a time?


Is there any way I can only replace only the first argument only in string formatting? Like in this:

"My quest is {test}{}".format(test="test")

I want the output to be:

"My quest is test {}

The second {} arg I will replace later.

I know I can create a string like:

"My quest is {test}".format(test="test")

and later combine it with remaining string and create new string, but can I do it in one go?


Solution

  • If you know when you set up the format string that you'll only be replacing a subset of the values, and you want some other set to remain, you can escape the ones you're not going to fill right away by doubling the brackets:

    x = "foo {test} bar {{other}}".format(test="test") # other won't be filled in here
    print(x)                              # prints "foo test bar {other}"
    print(x.format(other="whatever"))     # prints "foo test bar whatever"