如何阅读python字符串格式语法?
问题内容:
python文档包含有关格式化字符串的语法的信息,但是我似乎找不到有关如何读取定义替换字段语法的表的信息。
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>
格式规范部分中也有一个类似的表。
我了解表的各个部分,例如将::=
definiendum和definien分开,引号内的字符是文字,其|
含义是“或”,但是表的其余部分使我无所适从。
问题答案:
这种格式就是所谓的Backus-Naur
Form。在此处可以找到有关BNF的更多信息。基本上,BNF是一组派生规则。
定义符号:
- 除元符号:::,|和以<,>封闭的类名以外的任何其他字符都是所定义语言的符号(例如,此Python示例)
- 元符号:: =将被解释为“定义为”
- | 用于分隔替代定义,并解释为“或”
- 元符号<,>是包含类名的定界符。
剖析此示例以开始使用:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
replacement_field
由可选field_name
,可选conversion
和可选组成format_spec
。方括号([和]的)表示
可选参数 。
如果确实要传递field_name
给replacement_field
,则它包含一个arg_name
传递attribute_name
或
的函数element_index
。注意element_index
是强制性的,因为方括号用引号引起来,因此转义BNF格式为可选。