Hassek Hassek - 1 year ago 61
Python Question

python string format calling a function

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)

so it calls the function
function inside the string and not as a parameter in the format function.

Here is another example that will probably show my frustration better, this is what I would like:

"{0.full_name()} {0.full_last_name()} and my nick name is {0.full_nick_name()}".format(user)

this is what I want to avoid:

"{0} and {1} and my nick name is {2}".format(user.full_name(), user.full_last_name(), user.full_nick_name())

Answer Source

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