首页 » 编程开发 » Python » 正文

Python中用str.format()函数格式化字符串方法实例

从python2.6开始,python新增了一种格式化字符串的函数str.format(),相比于之前用%符号格式化字符串的方法,str.format方法可谓是功能强大,操作简单,本文在这里介绍一些str.format函数使用的方法供大家参考。

>>> “Name: %s, age: %d” % (‘John’, 35)
‘Name: John, age: 35’
>>> i = 45
>>> ‘dec: %d/oct: %#o/hex: %#X’ % (i, i, i)
‘dec: 45/oct: 055/hex: 0X2D’
>>> “MM/DD/YY = %02d/%02d/%02d” % (12, 7, 41)
‘MM/DD/YY = 12/07/41’
>>> ‘Total with tax: $%.2f’ % (13.00 * 1.0825)
‘Total with tax: $14.07’
>>> d = {‘web’: ‘user’, ‘page’: 42}
>>> ‘http://xxx.yyy.zzz/%(web)s/%(page)d.html’ % d
‘http://xxx.yyy.zzz/user/42.html’

下面这些是跟上面等价的方法,请看例子:

>>> “Name: {0}, age: {1}”.format(‘John’, 35)
‘Name: John, age: 35’
>>> i = 45
>>> ‘dec: {0}/oct: {0:#o}/hex: {0:#X}’.format(i)
‘dec: 45/oct: 0o55/hex: 0X2D’
>>> “MM/DD/YY = {0:02d}/{1:02d}/{2:02d}”.format(12, 7, 41)
‘MM/DD/YY = 12/07/41’
>>> ‘Total with tax: ${0:.2f}’.format(13.00 * 1.0825)
‘Total with tax: $14.07’
>>> d = {‘web’: ‘user’, ‘page’: 42}
>>> ‘http://xxx.yyy.zzz/{web}/{page}.html’.format(**d)
‘http://xxx.yyy.zzz/user/42.html’
python2.6以后等所有版本,都可以通用兼容str.format()方法。

发表评论