这两段代码的效果是一样的:
from string import Template
template = Template('hi, ${name}')
msg = template.substitute(name=u'张三')
print msg
与
msg = u'hi, {name}'
msg = msg.format(name=u'张三')
print msg
我的问题是, string.Template与str.format谁的历史更久? 为什么会出现功能一样的库呢? 是不是一个是另一个的替代品呢?
The subject mentioned in my comment
%
,在str.format()
There is this passage in the official document (str.format - python2):Probably means:
So the original question mentioned the alternative of
Template
和format
是不是有替代关系,实际情况是,那俩家伙并没有,反而format
却真的是%
.Since the official said so, I recommend that you use it
format
就不要用%
when it comes to string formatting operations in the future.Original answer:
Template
是string
模块里的类,format
是__buildin__
Built-in functions in the module, this is the fundamental difference between the two.Since it is a class, you can inherit it and rewrite the content according to your own needs. For example, the default delimiter
$
can be modified by us:Output result:
In the same way, we can also do more things we want. This is the "private customization" that can be achieved as a class.
In addition, regarding
format
, its application range is actually very wide. In addition to what you mentioned in your example, we also commonly use the following:And the very important padding alignment, precision, and even base conversion:
So the application directions of
Template
andTemplate
和format
are completely different.Why aren’t you surprised why the sorted function and list.sort() exist at the same time?
Functions with similar functions are generally aimed at special application scenarios, for example, sorted has a return value and sort directly changes the object.
For string.Template and str.format, string.Template, as its name states, is suitable for defining templates and can be used later. For example, if you define a template in a function or package, it can be conveniently used at any time. Called without knowing its details. The str.format() is generally used for single-line expressions and is more flexible to use.