python字符串格式调用函数

2022-01-15 00:00:00 python python-3.x format

问题描述

有没有办法用新的格式语法格式化来自函数调用的字符串?例如:

Is there a way to format with the new format syntax a string from a function call? for example:

"my request url was {0.get_full_path()}".format(request)

所以它调用函数get_full_path函数inside字符串而不是作为格式函数中的参数.

so it calls the function get_full_path function inside the string and not as a parameter in the format function.

这是另一个可能会更好地表达我的挫败感的例子,这就是我想要的:

Here is another example that will probably show my frustration better, this is what I would like:

"{0.full_name()} {0.full_last_name()} and my nick name is {0.full_nick_name()}".format(user)

这是我想要避免的:

"{0} and {1} and my nick name is {2}".format(user.full_name(), user.full_last_name(), user.full_nick_name())


解决方案

Python 3.6 添加了文字字符串插值,它是用 f 前缀编写的.请参阅 PEP 0498 -- 文字字符串插值.

Python 3.6 adds literal string interpolation, which is written with an f prefix. See PEP 0498 -- Literal String Interpolation.

这样可以写

>>> x = 'hello'
>>> s = f'{x}'
>>> print(s)
hello

应该注意,这些不是实际的字符串,而是表示每次都计算为字符串的代码.在上面的示例中,s 的类型为 str,值为 'hello'.你不能传递一个 f-string,因为它会在使用前被评估为结果 str(不像 str.format,但与所有其他字符串文字修饰符一样,例如 r'hello'b'hello''''hello''').(PEP 501 -- 通用字符串插值(目前推迟)建议使用字符串将评估为稍后可以进行替换的对象的文字.)

It should be noted that these are not actual strings, but represent code that evaluates to a string each time. In the above example, s will be of type str, with value 'hello'. You can't pass an f-string around, since it will be evaluated to the result str before being used (unlike str.format, but like every other string literal modifier, such as r'hello', b'hello', '''hello'''). (PEP 501 -- General purpose string interpolation (currently deferred) suggests a string literal that will evaluate to an object which can take substitutions later.)

相关文章