Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 571
sagar Avatar asked Nov 18 '16 07:11

sagar


People also ask

Which formatting methods in Python 3 allows multiple substitutions and value formatting?

Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

What is the argument specifier for a string?

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".


1 Answers

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"
like image 144
Blckknght Avatar answered Sep 28 '22 06:09

Blckknght