4

%モジュロまたは文字列フォーマッタでない場合、記号は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)

この演算子が何であるかについてGoogleとSOを検索しましたが、運がありません。私は python 2.6.1 を使用しています。

4

2 に答える 2

9

それも文字列フォーマットです。構文は、%(var)フォーマット置換の辞書を渡すときに使用され、それぞれが名前に置き換えられます。

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

これは、ドキュメントに記載されている「マッピング キー」の使用法です。

于 2012-07-29T06:01:56.853 に答える
4

これは、フォーマット指定子としての使用です。

>>> print '%(b)s %(a)s' % { 'a': "world", 'b': "hello" }
hello world
于 2012-07-29T06:02:34.153 に答える