标签:except spec idt 求值 object number color exce 空字符串
3.6 新版功能
格式化字符串(f-string
),是带有 f
或 F
前缀的字符串。
这种字符串可包含替换字段,替换字段是以 { }
标示的表达式。
f_string ::= (literal_char | "{{" | "}}" | replacement_field)*
replacement_field ::= "{" f_expression ["!" conversion] [":" format_spec] "}"
f_expression ::= (conditional_expression | "*" or_expr)
("," conditional_expression | "," "*" or_expr) *
[","] | yield_expression
conversion ::= "s" | "r" | "a"
format_spec ::= (literal_char | NULL | replacement_field)*
literal_char ::= <any code point except "{", "}" or NULL>
{ { } }
: 双花括号会被替换为响应的单个花括号。
{ }
: 单花括号标志一个替换字段,以一个 Python
表达式开头。
!
标示的转换字段。:
标示的格式说明符。conversion
:转换符
如果指定了转换符,表达式的求值结果会先转换再格式化
!s
------------------ str()
返回 object
的字符串版本。如果未提供 object
则返回空字符串
!r
------------------repr()
返回包含一个对象的可打印形式的字符串。
!a
------------------ascii()
返回一个对象的可打印的 ASCII
编码的字符串。
format_spec
: 格式化说明符
format_spec
控制的格式化表示。例
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."
>>> f"He said his name is {repr(name)}." # 使用 !r
"He said his name is 'Fred'."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # 表达式格式化
'result: 12.35'
>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # 格式化日期
'January 27, 2017'
>>> number = 1024
>>> f"{number:#0x}" # 进制转化
'0x400'
标签:except spec idt 求值 object number color exce 空字符串
原文地址:https://www.cnblogs.com/wdzn/p/12244656.html