python string format calling a function

前端 未结 5 767
情书的邮戳
情书的邮戳 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
    
    0 讨论(0)
  • 2020-12-06 05:01

    What about this very weird thing?

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

    Explanation:

    1. Classic way of formatting
    2. Lambda function which takes a request and returns a tuple with what you want
    3. Call the lambda inline as arguments for your string.

    I still prefer the way you're doing it.

    If you want readability you can do this:

    path, post = request.get_full_path(), request.POST
    "my request url was {} and my post was {}".format(path, post)
    
    0 讨论(0)
  • 2020-12-06 05:02

    Python 3.6 adds literal string interpolation, which is written with an f prefix. See PEP 0498 -- Literal String Interpolation.

    This allows one to write

    >>> x = 'hello'
    >>> s = f'{x}'
    >>> print(s)
    hello
    

    It should be noted that these are not actual strings, but represent code that evaluates to a string each time. In the above example, s will be of type str, with value 'hello'. You can't pass an f-string around, since it will be evaluated to the result str before being used (unlike str.format, but like every other string literal modifier, such as r'hello', b'hello', '''hello'''). (PEP 501 -- General purpose string interpolation (currently deferred) suggests a string literal that will evaluate to an object which can take substitutions later.)

    0 讨论(0)
  • 2020-12-06 05:12

    Not sure if you can modify the object, but you could modify or wrap the object to make the functions properties. Then they would look like attributes, and you could do it as

    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)
    

    which IS legal.

    0 讨论(0)
  • 2020-12-06 05:14

    Python does not directly support variable interpolation. This means that it lacks certain functionality (namely, function calling in strings) which other languages support.

    So, there isn't really anything to say here other than no, you can't do that. That's just not how Python's formatting syntax works.

    The best you have is this:

    "my request url was {0}".format(request.get_full_path())
    
    0 讨论(0)
提交回复
热议问题