How to define a python constant (quasi) that has dynamic inputs?

For instance:

MY_MESSAGE = 'Dear %s, hello.' # ... name = "jj" print MY_MESSAGE % name 

Does python have a function to execute something like my above code?

+4
source share
4 answers

Yes, exactly as you wrote it. Your code is ok.

+5
source

Python really does not have the same concept of "constant" that you will find in C. So you have a pretty good approach.

I would actually argue that this is one example of the fact that β€œwe all agree with adults” does not hold well. Think that the language is awesome, but constant every time will be ... enjoyable.

+3
source

The string format operator:% can also do other neat things:

 STRING = "This is %(foo)s, and this is also %(foo)s" print STRING % {"foo": "BAR"} # => This is BAR, and this is also BAR 

This is really useful if you will repeat one argument. Of course blows

 FORMAT_STRING % ("BAR", "BAR") 

You can also register and format numbers.

+2
source

Your code is correct, but I believe there is a preferable way to do this:

 >>> my_message = 'Dear {:s}, hello.' >>> my_message.format('jj') 'Dear jj, hello.' 

Preferably, due to a possible future replacement of the % operator with the .format() method.

As mentioned in Mark Lutz Learning Python. Fourth edition, format method:

  • has several functions not found in the % expression,
  • can make substitution values ​​more explicit,
  • trades the operator, perhaps more than the name of the mnemonic method,
  • does not support different syntax for single and multiple substitution cases,

and then in the same book:

... there is some risk that Python developers may refuse the % expression in favor of the format method in the future. In fact, there is a note in the Python 3.0 manual.

+1
source

All Articles