有没有办法用新格式语法格式化函数调用的字符串?例如:
"my request url was {0.get_full_path()}".format(request)
所以它在字符串中调用函数get_full_path函数而不是format函数中的参数.
编辑:
这是另一个可能更好地表达我的挫败感的例子,这就是我想要的:
"{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())
解决方法:
这允许一个人写
>>> x = 'hello'
>>> s = f'{x}'
>>> print(s)
hello
应该注意的是,这些不是实际的字符串,而是表示每次都计算为字符串的代码.在上面的例子中,s的类型为str,值为’hello’.你不能传递一个f-string,因为它在被使用之前会被计算到结果str(与str.format不同,但是像所有其他字符串文字修饰符一样,例如r’hello’,b’hello’,’ ”你好”’). (PEP 501 — General purpose string interpolation(当前是延迟的)建议一个字符串文字,它将评估一个可以在以后进行替换的对象.)
标签:python,python-3-x,format
来源: https://codeday.me/bug/20191001/1838198.html