gpt4 book ai didi

python - "executes"是一个 f-string 的内部函数的名称是什么?

转载 作者:行者123 更新时间:2023-12-05 06:17:10 25 4
gpt4 key购买 nike

我读过 How do I convert a string into an f-string?How to postpone/defer the evaluation of f-strings?并且已经看到许多使用 exec 来推迟执行 f 字符串的(有效的)解决方案,例如:

template = "My name is {name} and I am {age} years old"
name = 'Abcde'
age = 123
s = eval('f"""' + template + '"""') # My name is Abcde and I am 123 years old

是否有一个内部 Python 函数(在许多双下划线 __something__ 函数中)定义了解释器如何“运行”/“插入”f 字符串?

Python源码中有没有类似__runfstring__的东西,负责代码的执行?如果是这样,我们可以自己调用这个函数吗?

s = __runfstring__(template)

在最新的 Python 版本中? (3.7 或 3.8+)

最佳答案

Is there an internal Python function (among the many double underscode __something__ functions), that defines how the interepreter "runs" / "interpolates" a f-string

答案是。来自 PEP 498其中介绍了 f 弦:

The exact code used to implement f-strings is not specified. However, it is guaranteed that any embedded value that is converted to a string will use that value's __format__ method. This is the same mechanism that str.format() uses to convert values to strings.

来自关于 Lexical Analysis 的文档在 Formatted string literals部分:

If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion '!s' calls str() on the result, '!r' calls repr(), and '!a' calls ascii().

The result is then formatted using the format() protocol. The format specifier is passed to the __format__() method of the expression or conversion result. An empty string is passed when the format specifier is omitted. The formatted result is then included in the final value of the whole string.

所以没有新的为他们实现。它们建立在现有协议(protocol)之上。

关于python - "executes"是一个 f-string 的内部函数的名称是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61751964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com