2

What I want to do is:

property = "name"
formatter = "my %s is %s" % property
print formatter % "wong2" // "my name is wong2"

but the first line gives "not enough arguments for format string" error.

5 Answers 5

4
>>> property = "name"
>>> formatter = "my %s is %%s" % property
>>> print formatter % "wong2"
my name is wong2
Sign up to request clarification or add additional context in comments.

Comments

3

A double-percent will create a single-percent sign after formatting:

formatter = "my %s is %%s"

Comments

1

You can escape a formatter by doubling it

formatter = "my %s is %%s" % property

You can also do all substitutions at the same time using by-name instead of positional formatting:

formatter = "my %(property)s is %(name)s"
print formatter % { "property": "name",
                    "name": "wong2" }

This forms allows for a variable number of substitutions (i.e. not all keys in the dictionary needs to be used and they may be used more than once). This is important if for example the format string is read from a configuration file.

Comments

1

Here's a fun way to do it with a helper class

>>> property = "name"
>>> class D(dict):
...     def __missing__(self, key):
...         return "%("+key+")s"
... 
>>> formatter = "my %(property)s is %(value)s"%D(property=property)
>>> formatter%D(value="wong2")
'my name is wong2'

Comments

1

I personally don't like the % formatting syntax, so I'll suggest quite the same as previous answers but using the format syntax:

property = 'name'
formatter = "my {} is {{}}".format(property) #=> "my name is {}"
print formatter.format('wong')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.