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 get_full_path
function inside the string and not as a parameter in the format function.
EDIT: 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())
Use locals() and globals() to Call a Function From a String in Python. Another way to call a function from a string is by using the built-in functions locals() and globals . These two functions return a Python dictionary that represents the current symbol table of the given source code.
The formatting using % is similar to that of 'printf' in C programming language. %d – integer %f – float %s – string %x – hexadecimal %o – octal The below example describes the use of formatting using % in Python.
Here's what python.org has to say about %i: Signed integer decimal. And %d: Signed integer decimal. %d stands for decimal and %i for integer. but both are same, you can use both.
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With