python字符串格式调用一个函数 [英] python string format calling a function

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

问题描述

有没有一种方法来格式化新的格式语法从函数调用的字符串?例如:

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

所以它调用函数 get_full_path 函数编辑:
这里是另一个例子,可能会更好地显示我的挫折,这是什么我想:

 {0.full_name()} {0.full_last_name()}和我的昵称是{0 .full_nick_name()}。format(user)

这就是我想要避免的:格式(user.full_name(),user)。用户名和密码都是{0}和{1},我的昵称是{2}。 full_last_name(),user.full_nick_name())


解决方案

3.6增加了用 f 前缀写入的字符串插值。请参阅 PEP 0498 - 文字字符串插值



这允许写一个

 >>> x ='hello'
>>> s = f'{x}'
>>>打印
hello

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

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)

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

EDIT: 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)

this is what I want to avoid:

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

解决方案

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

This allows one to write

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

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字符串格式调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆