嵌套 f 弦 [英] Nested f-strings

查看:28
本文介绍了嵌套 f 弦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢 David Beazley 的推文,我最近发现新的 Python 3.6 f-strings 也可以嵌套:

<预><代码>>>>价格 = 478.23>>>f"{f'${price:0.2f}':*>20s}"'**************** 478.23 美元'

或者:

<预><代码>>>>x = 42>>>f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-''''-*+.42.+*-'

虽然我很惊讶这是可能的,但我不知道这有多实用,嵌套 f 字符串什么时候有用?这可以涵盖哪些用例?

注意:PEP 本身没有提到嵌套 f 字符串,但是有一个 特定的测试用例.

解决方案

我不认为格式化的字符串文字允许嵌套(通过嵌套,我认为它意味着 f'{f".."}') 是仔细考虑可能的用例的结果,我更相信它只是为了让他们符合他们的规范.

规范声明他们支持完整的 Python 表达式* 括号内.它还指出,格式化的字符串文字实际上只是一个在运行时计算的表达式(参见 此处此处).因此,只允许一个格式化字符串文字作为另一个格式化字符串文字中的表达式才有意义,禁止它会否定对 Python 表达式的完全支持.

您找不到文档中提到的用例(并且只能在测试套件中找到测试用例)的事实是因为这可能是实现的一个很好的(副作用)效果,而不是它的激励用例.

<小时>

实际上,有两个例外:一个空表达式是不允许的,一个 lambda 表达式必须用显式括号括起来.

Thanks to David Beazley's tweet, I've recently found out that the new Python 3.6 f-strings can also be nested:

>>> price = 478.23
>>> f"{f'${price:0.2f}':*>20s}"
'*************$478.23'

Or:

>>> x = 42
>>> f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-'''
'-*+.42.+*-'

While I am surprised that this is possible, I am missing on how practical is that, when would nesting f-strings be useful? What use cases can this cover?

Note: The PEP itself does not mention nesting f-strings, but there is a specific test case.

解决方案

I don't think formatted string literals allowing nesting (by nesting, I take it to mean f'{f".."}') is a result of careful consideration of possible use cases, I'm more convinced it's just allowed in order for them to conform with their specification.

The specification states that they support full Python expressions* inside brackets. It's also stated that a formatted string literal is really just an expression that is evaluated at run-time (See here, and here). As a result, it only makes sense to allow a formatted string literal as the expression inside another formatted string literal, forbidding it would negate the full support for Python expressions.

The fact that you can't find use cases mentioned in the docs (and only find test cases in the test suite) is because this is probably a nice (side) effect of the implementation and not it's motivating use-case.


Actually, with two exceptions: An empty expression is not allowed, and a lambda expression must be surrounded by explicit parentheses.

这篇关于嵌套 f 弦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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