Has*_*sek 18 python format python-3.x
有没有办法用新格式语法格式化函数调用的字符串?例如:
"my request url was {0.get_full_path()}".format(request)
Run Code Online (Sandbox Code Playgroud)
所以它调用该函数get_full_path的功能里面的字符串,而不是作为格式功能的参数.
编辑:这是另一个可能更好地表明我的挫败感的例子,这就是我想要的:
"{0.full_name()} {0.full_last_name()} and my nick name is {0.full_nick_name()}".format(user)
Run Code Online (Sandbox Code Playgroud)
这是我想要避免的:
"{0} and {1} and my nick name is {2}".format(user.full_name(), user.full_last_name(), user.full_nick_name())
Run Code Online (Sandbox Code Playgroud)
Cor*_*man 18
不确定是否可以修改对象,但可以修改或包装对象以生成函数属性.然后他们看起来像属性,你可以这样做
class WrapperClass(originalRequest):
@property
def full_name(self):
return super(WrapperClass, self).full_name()
"{0.full_name} {0.full_last_name} and my nick name is {0.full_nick_name}".format(user)
Run Code Online (Sandbox Code Playgroud)
这是合法的.
lee*_*ewz 11
Python 3.6添加了文字字符串插值,它使用f前缀编写.参见PEP 0498 - 文字字符串插值.
这允许一个人写
>>> x = 'hello'
>>> s = f'{x}'
>>> print(s)
hello
Run Code Online (Sandbox Code Playgroud)
应该注意的是,这些不是实际的字符串,而是表示每次都计算为字符串的代码.在上面的例子中,s将是str有价值的类型'hello'.你不能传递一个f围绕-string,因为它会进行评估,结果str在使用之前(不像str.format,但就像其他字符串文字修饰,比如r'hello',b'hello','''hello''').(PEP 501 - 通用字符串插值(当前是延迟的)建议一个字符串文字,它将评估一个可以在以后进行替换的对象.)
Python不直接支持变量插值.这意味着它缺少其他语言支持的某些功能(即,字符串中的函数调用).
所以,除了不,没有什么可说的,你不能这样做.这不是Python的格式化语法的工作原理.
你最好的是:
"my request url was {0}".format(request.get_full_path())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12457 次 |
| 最近记录: |