python string format calling a function(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字符串格式调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python字符串格式调用函数
基础教程推荐
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
