3

What does a % sign mean in python when it is not a modulo or a string formatter? I came across it in this baffling block of code in the timeit module:

# Don't change the indentation of the template; the reindent() calls # in Timer.__init__() depend on setup being indented 4 spaces and stmt # being indented 8 spaces. template = """ def inner(_it, _timer): %(setup)s _t0 = _timer() for _i in _it: %(stmt)s _t1 = _timer() return _t1 - _t0 """ def reindent(src, indent): """Helper to reindent a multi-line statement.""" return src.replace("\n", "\n" + " "*indent) 

I have searched Google and SO for what this operator is, but no luck. I am using python 2.6.1 .

1
  • It is string formatting here. Notice the """ symbols? There is a variable template in the code, and it is being assigned a string. The % is used for formatting, just like usual. It's just that the actual substitution hasn't happened yet in this part of the code. Commented Jan 12, 2023 at 1:14

2 Answers 2

9

That is also string formatting. The %(var) syntax is used when you pass a dictionary of format replacers, and each is replaced by name:

>>> "%(foo)s is replaced" % {'foo': 'THIS'} 'THIS is replaced' 

This is the "mapping key" usage described in the documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh. Right. I was so distracted by the odd technique of writing out an entire method in a string that I forgot it could be string formatting because it would be replaced later in the program. I thought, "Oh cool- a new % usage." Kinda dumb on my part. Thanks.
@MatthewAdams I wouldn't say it's dumb since % formatting was deprecated for a good reason.
4

This is its use as a format specifier.

>>> print '%(b)s %(a)s' % { 'a': "world", 'b': "hello" } hello world 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.