嵌套的f弦 [英] Nested f-strings

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

问题描述

由于 David Beazley的推文,我最近发现新的Python 3.6 f字符串也可以嵌套:

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

或者:

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

虽然我对此感到惊讶,但我却不知道这样做的实用性,何时嵌套f字符串会有用?这可以涵盖哪些用例?

注意:PEP本身没有提到嵌套f字符串,但是有一个解决方案

我不认为允许嵌套的格式化字符串文字(通过嵌套,我指的是f'{f".."}')不是仔细考虑可能的用例的结果,我更坚信这是为了使它们符合其规范而被允许的.

规范指出,它们支持完整的Python 表达式 *放在方括号内.还指出,格式化的字符串文字实际上只是一个在运行时求值的表达式(请参见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天全站免登陆