继续学习Python。网上到处有人说Python容易学习,但是我只能部分赞成:语法比较简单、变量无需定义这是容易学习的地方;庞大的标准库及扩展、过于‘灵活’的特性(比如lambda、装饰器、列表推导等等函数式特性)都是不容易掌握的地方(对我来说是)。
###############################分割线###(学习要不畏艰难,请无视上面那段)
关于Python中格式化字符串,比较常用的是“%” :有各种%s,%d,%u……,这里不介绍了,详情见Google。这里要主要介绍的是:Python2.7.3文档中7.1.3.节的部分内容和str.format()方法。
我们暂且将要输出的字符串称作‘格式串’,格式串中包含要被替换掉的部分称作’替换域‘,输出时替换域的内容应该是’填充域‘。例如"I am a %s" % 'student'中I am a %s就是格式串,%s为替换域,student为填充域。
python除了用’%‘表示替换域以外,还可以用大括号'{}',例如:
"First, thou shalt count to {0}"
再多看几个例子:
>>> "First, thou shalt count to {0}".format(10)
'First, thou shalt count to 10' #大括号里的内容被替换成了10
>>> "From {0} to {1}".format('BeiJing','ShangHai')
'From BeiJing to ShangHai' #0、1可以看做索引、2.7以后可以省略
>>> "My quest is {name}".format(name="YueZheng")
'My quest is YueZheng' #大括号里也可以放变量
>>> "Units destroyed: {players[0]}".format(players=['a','b'])
'Units destroyed: a'
>>> class people():
... def __init__(self,weight=75):
... self.weight = weight
...
>>> YueZheng = people()
>>> "Weight in tons {0.weight}".format(YueZheng)
'Weight in tons 75' #对象的属性也可以
另外还可以通过
'!s'或'!r'来设定具体用str()还是用repr()方法来显示,关于这两个方法的具体说明请Google。
"Harold's a clever {0!s}" # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first
还有一个比较关键的特性,就是支持参数中序列和字典的解包:
>>> '{2}, {1}, {0}'.format(*'abc')
'c, b, a'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
关于{}方式的字符串格式化的内容基本就是这些了,是不是感觉很简单?用这种方式,’Template‘的感觉更明显了。不过还有很多东西没有深入研究,像2.6中新引进的Formatter类如何使用、对象的魔术方法
__format__()等等。