Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python usage of percentage sign- doesn't appear to be modulo or string formatting

Tags:

python

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 .

like image 392
Matthew Adams Avatar asked Dec 11 '22 23:12

Matthew Adams


2 Answers

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.

like image 170
BrenBarn Avatar answered Apr 19 '23 22:04

BrenBarn


This is its use as a format specifier.

>>> print '%(b)s %(a)s' % { 'a': "world", 'b': "hello" }
hello world
like image 27
Dietrich Epp Avatar answered Apr 19 '23 23:04

Dietrich Epp