python string format calling a function

前端 未结 5 782
情书的邮戳
情书的邮戳 2020-12-06 04:16

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)
         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 04:57

    So summary of methods would be

    (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
    

提交回复
热议问题