百分号的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)

我已经在 Google 和 SO 上搜索过这个运算符是什么,但没有成功。我正在使用 python 2.6.1。

最佳答案

这也是字符串格式化。 %(var) 语法在传递格式替换器字典时使用,每个替换器都由名称替换:

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

这是 the documentation 中描述的“映射键”用法.

关于百分号的python用法-似乎不是模数或字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11707046/

相关文章:

python - python程序运行完成后如何自动重新运行?主管?

Python - 使用 NLTK 搜索文本

python - 如何将 python-trio 与谷歌 Protocol Buffer 一起使用?

python - 如何从列表中删除逗号

python - 如何在python的elasticsearch中索引大型json响应?使用Elasticsearch DSL

python - 创建一个将华氏温度转换为摄氏度的函数

python - 为什么 CPython 不将文字结果存储为代码对象的常量?

python - 在 python 中获取列表

python - 从本地 python 脚本执行远程 python 脚本时出错

python - 将日期从字符串格式转换为 OLE 自动化日期