开发者

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

For example:

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

Does python have a feature for accomplishing something like 开发者_如何学编程my above code?


Yes, the exact way you wrote it. Your code is fine.


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

I would actually argue that this is one example of "we're all consenting adults" does not hold up terribly well. Think the language is awesome, but a constant every now and again would be... nice.


The string formatting 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 be repeating one argument. Sure beats

FORMAT_STRING % ("BAR", "BAR")

You can also do padding, and number formatting.


Your code is correct, but I believe there is a more preferred way to do that:

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

Preferred, because of possible future replacement of % operator by .format() method.

As mentioned in Mark Lutz's Learning Python. Fourth Edition, format method:

  • has a few features not found in the % expression,
  • can make substitution values more explicit,
  • trades an operator for arguably more mnemonic method name,
  • does not support different syntax for single and multiple substitution value cases,

and later, in the same book:

... there is some risk that Python developers may deprecate the % expression in favor of the format method in the future. In fact, there is a note to that effect in Python 3.0's manuals.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜