Skip to main content
 首页 » 编程设计

python之这段代码 : %(var)s Python 可能是什么

2025年05月04日13qq78292959

我使用的网站后端有一个选项,允许我在为产品下订单时自定义 CSV 文件中发送的数据。有两列,左列是您分配标题的位置,右列是您输入变量的位置。现有变量的语法类似于 %(order.random_variable)s 或 %(item.random_variable)s 这看起来类似于字符串占位符 %s 在 Python 中,我相当有信心它是相关的,即使不相同,但我不太理解语法。有人可以详细说明这段代码的用途吗?

哦,郑重声明,我不打算立即进入并更改变量。只是为我的研究寻找一个好的起点。

请您参考如下方法:

这类似于%s。括号内的部分是可选的。

The only difference is that, for the first one, your values must be a tuple with exactly the number of items specified by the format string, and for the 2nd one, it must be a single mapping object (for example, a dictionary)

它在String formatting documentation 中明确列出:-

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

  1. The '%' character, which marks the start of the specifier.
  2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
    .. and there are some more

另外:-

When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping

文档中的示例:-

>>> print '%(language)s has %(number)03d quote types.' % \ 
...       {"language": "Python", "number": 2} 
Python has 002 quote types. 

因此,在 % 之后和 s 之前的 () 中的文本是字典中的一个 key .