python string format calling a function

前端 未结 5 792
情书的邮戳
情书的邮戳 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 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)
    

提交回复
热议问题