python字符串格式调用函数

2023-06-06Python开发问题
11

本文介绍了python字符串格式调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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.)

这篇关于python字符串格式调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10