如何阅读python字符串格式化语法? [英] How to read the python string formatting grammar?

查看:34
本文介绍了如何阅读python字符串格式化语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 文档有关于格式化字符串的语法信息,但是我似乎无法找到有关如何阅读定义替换字段语法的表的信息.

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>

格式规范部分中也有类似的表格.

我理解表格的某些部分,例如 ::= 将定义和定义分开,引号内的字符是文字​​,| 表示或",但是桌子的其余部分让我望而却步.

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.

推荐答案

这种格式就是所谓的 Backus-Naur 格式.在这里可以找到有关 BNF 的更多信息. 基本上,BNF 是一组推导规则.

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.

定义符号:

  • 除了元符号 ::=、| 和 <,> 中封闭的类名之外的任何东西都是所定义语言的符号(例如这个 Python 示例)
  • 元符号 ::= 被解释为被定义为"
  • 该 |用于分隔替代定义并解释为或"
  • 元符号 <,> 是包含类名的分隔符.

稍微剖析一下这个例子,让你开始:

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 由可选的 field_name、可选的 conversion 和可选的 format_spec 组成.方括号( [ 和 ] 的)表示可选参数.

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

如果您确实将field_name 传递给replacement_field,它包含一个arg_name 函数,您可以在其中传递attribute_name element_index.注意 element_index 是强制性的,因为括号是在引号中,因此可以将 BNF 形式转义为可选.

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.

这篇关于如何阅读python字符串格式化语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆