有没有办法使用新的格式语法格式化函数调用中的字符串?
例如:
"my request url was {0.get_full_path()}".format(request)
因此它调用函数
get_full_path()
函数inside字符串而不是作为格式函数中的参数。
这是另一个例子,可能会更好地展示我的挫败感,这就是我想要的:
"{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())
不确定是否可以修改该对象,但可以修改或包装该对象以创建函数属性。然后它们看起来像属性,你可以这样做
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)
这是合法的。
Python 3.6 添加了文字字符串插值,它以
f
前缀编写。请参阅PEP 0498 -- 文字字符串插值。
这允许人们书写
>>> x = 'hello'
>>> s = f'{x}'
>>> print(s)
hello
应该注意的是,这些不是实际的字符串,而是代表每次计算结果为字符串的代码。在上面的示例中,
s
的类型为 str
,值为 'hello'
。您不能传递 f
字符串,因为在使用之前它将被评估为结果 str
(与 str.format
不同,但与所有其他字符串文字修饰符一样,例如 r'hello'
、b'hello'
) ,'''hello'''
)。 (PEP 501 - 通用字符串插值(当前已推迟)建议使用一个字符串文字,该字符串文字将计算为稍后可以进行替换的对象。)
Python 3.6 之前的版本不直接支持变量插值。这意味着它缺乏其他语言支持的某些功能(即字符串中的函数调用)。
所以,除了“不”之外,没有什么可说的,在 3.6 之前你不能这样做。 Python 的格式化语法并不是这样工作的。
你拥有的最好的就是这个:
"my request url was {0}".format(request.get_full_path())
这个很奇怪的事情是怎么回事?
"my request url was %s and my post was %s"\
% (lambda r: (r.get_full_path(), r.POST))(request)
说明:
我还是更喜欢你的做法。
如果你想要可读性,你可以这样做:
path, post = request.get_full_path(), request.POST
"my request url was {} and my post was {}".format(path, post)
所以方法总结是
(base) [1]~ $ cat r.py
# user is dict:
user = {'full_name': 'dict joe'}
print('{0[full_name]}'.format(user))
# user is obj:
class user:
@property
def full_name(self):
return 'attr joe'
print('{0.full_name}'.format(user()))
# Wrapper for arbitray values - as dict or by attr
class Getter:
def __init__(self, src):
self.src = src
def __getitem__(self, k):
return getattr(self.src, k, 'not found: %s' % k)
__getattr__ = __getitem__
print('{0[foo]} - {0.full_name}'.format(Getter(user())))
(base) [1]~ $ python r.py
dict joe
attr joe
not found: foo - attr joe