Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string format calling a function

Tags:

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()) 
like image 868
Hassek Avatar asked Nov 05 '13 18:11

Hassek


People also ask

How do you call a function inside a string in Python?

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.

What is %s %d %F in Python?

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.

What is %d and %i 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.

How do I format a function in a string?

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.


1 Answers

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.

like image 186
Corley Brigman Avatar answered Oct 04 '22 18:10

Corley Brigman