【发布时间】:2019-09-19 21:13:03
【问题描述】:
在 python 文档 2.4.3. Formatted string literals 中,似乎可以在 f 字符串的 {} 中写一个星号,后跟一个表达式,但我找不到如何使用它。
那是什么以及如何使用它?它是否记录在某处?
确切地说,这是关于 "*" or_expr 以下BNF 的一部分。
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
我在 REPL 中尝试过,但它会导致错误。
>>> l = [1, 2, 3]
>>> f"{l}"
'[1, 2, 3]'
>>> f"{*l}"
File "<stdin>", line 1
SyntaxError: can't use starred expression here
【问题讨论】:
-
看看这里:realpython.com/python-f-strings。他们为 python 支持字符串格式化的新方法提供了一个很好的列表。公平地说,我这辈子从来没有见过这种星号。也许这是新事物。希望对您有所帮助。
标签: python python-3.x string language-lawyer f-string