How to read the python string formatting grammar?

情到浓时终转凉″ 提交于 2019-11-30 17:41:31

问题


The python documentation has information on the grammar of formatting strings, however I can't seem to find information on how to read the table defining the grammar for the replacement field.

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | integer]
attribute_name    ::=  identifier
element_index     ::=  integer | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>

There's also a similar table in the format specification section.

I understand portions of the table, like the ::= separates the definiendum and definien, characters inside quotes are literals, and the | means "or", but the rest of the table escapes me.


回答1:


This kind of formatting is what's known as Backus-Naur Form. More information found on BNF here. Basically, BNF is a set of derivation rules.

Defining the symbols:

  • Anything other than the meta symbols ::=, |, and class names in closed in <,> are symbols of the language being defined (e.g. This Python example)
  • The meta symbols ::= is to be interpreted as "is defined as"
  • The | is used to separate alternative definitions and is interpreted as "or"
  • The meta symbols <,> are delimiters enclosing a class name.

A little bit of dissecting this example to get you started:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*

replacement_field consists of an optional field_name, optional conversion and optional format_spec. The brackets ( the [ and ]'s ) indicate optional parameters.

If you do pass in field_name to replacement_field, it consists of an arg_name function in which you pass attribute_name or element_index. Note element_index is mandatory because the brackets are in quotation marks, and thus escaping BNF form for optional.



来源:https://stackoverflow.com/questions/35216386/how-to-read-the-python-string-formatting-grammar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!