如何读取python字符串格式化语法?

问题描述 投票:4回答:1

python文档有关于formatting strings语法的信息,但是我似乎无法找到有关如何读取定义替换字段语法的表的信息。

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>

format specification section也有类似的表。

我理解表格的一部分,比如::=分隔了定义和definien,引号内的字符是文字​​,而|的意思是“或”,但桌子的其余部分逃脱了我。

python string-formatting
1个回答
2
投票

这种格式就是所谓的Backus-Naur形式。 More information found on BNF here.基本上,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_nameelement_index。注意element_index是强制性的,因为括号是引号,因此转出BNF表格可选。

© www.soinside.com 2019 - 2024. All rights reserved.