Python字符串格式调用函数

628mspwn  于 2023-06-07  发布在  Python
关注(0)|答案(5)|浏览(578)

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

"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())
jhkqcmku

jhkqcmku1#

不确定是否可以修改对象,但可以修改或 Package 对象以使函数具有属性。然后它们看起来就像属性,你可以这样做

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)

这是法律的的。

dsekswqp

dsekswqp2#

Python 3.6添加了文字字符串插值,它是用f前缀编写的。参见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 -- General purpose string interpolation(当前延迟)建议一个字符串字面量,该字符串字面量将计算为一个稍后可以进行替换的对象。

5rgfhyps

5rgfhyps3#

Python不直接支持变量插值。这意味着它缺乏其他语言支持的某些功能(即字符串中的函数调用)。
所以,这里没有什么可说的,除了不,你不能这么做。这不是Python的格式化语法的工作方式。
你最好的是这个:

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

xpcnnkqh4#

这个奇怪的东西呢?

"my request url was %s and my post was %s"\
    % (lambda r: (r.get_full_path(), r.POST))(request)

说明:
1.经典的格式化方式

  1. Lambda函数,它接受一个请求,并返回一个包含你想要的元组
    1.调用lambda内联作为字符串的参数。
    我还是喜欢你这样做。
    如果你想要可读性,你可以这样做:
path, post = request.get_full_path(), request.POST
"my request url was {} and my post was {}".format(path, post)
4nkexdtk

4nkexdtk5#

因此,方法总结如下

(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

相关问题