python使用百分号 - 似乎不是模数或字符串格式

Mat*_*ams 4 python

%当python不是模数或字符串格式化时,符号在python中意味着什么?我在timeit模块中这个令人困惑的代码块中遇到了它:

# 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)
Run Code Online (Sandbox Code Playgroud)

我搜索谷歌和SO这个运营商是什么,但没有运气.我使用的是python 2.6.1.

Bre*_*arn 9

这也是字符串格式.%(var)传递格式替换器的字典时会使用该语法,并且每个替换为name:

>>> "%(foo)s is replaced" % {'foo': 'THIS'}
'THIS is replaced'
Run Code Online (Sandbox Code Playgroud)

这是文档中描述的"映射关键字"用法.

  • @MatthewAdams我不会说它是愚蠢的,因为`%`格式被弃用是有充分理由的. (2认同)