sagar sagar - 19 days ago 5
Python Question

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?

Answer

The only way you can replace it in the same line is if you replace "{test}" with another bracket. I.e:

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

but that doesn't make much sense because you could've just done:

s = "My quest is {test} {}".format('testing', test="test {}")

immediately.

You could keep the result of:

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

So s has a bracket inside it waiting to get replaced and call format on it later on if you need to.