这两段代码的效果是一样的:
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谁的历史更久? 为什么会出现功能一样的库呢? 是不是一个是另一个的替代品呢?
PHPz2017-04-18 09:31:24
The subject mentioned in my comment %
,在str.format()
There is this passage in the official document (str.format - python2):
This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.
Probably means:
This method was added in version
Python 3
中是新标准,开发人员应该首先使用它,而不是%
,来对字符串进行格式化操作。(format
是2.6
)
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.
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:
from string import Template
class MyTemp(Template):
delimiter = '#'
tem = MyTemp('hi, #{name}')
msg = tem.substitute(name='Jake')
print msg
Output result:
hi, Jake
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:
print 'Hi, {0}, {1}.'.format('Jake', 'Tom')
ppl = ['Jake', 'Tom']
print 'Hi, {0[0]}, {0[1]}.'.format(ppl)
# 输出结果都是 Hi, Jake, Tom.
And the very important padding alignment, precision, and even base conversion:
print '{:>5}'.format(100)
print '{:x>10}'.format(100)
print '{:.2f}'.format(100.02111)
print '{:b}'.format(15)
# 输出结果:
100
xxxxxxx100
100.02
1111
So the application directions of Template
and Template
和format
are completely different.
巴扎黑2017-04-18 09:31:24
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.
a = [1,3,2]
b = sorted(a)
b == [1,2,3]
a == [1,3,2]
a.sort()
a == [1,2,3]
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.