Python字符串格式化输出详解:占位符、format与Template
本文详解Python中实现字符串格式化输出的多种方法。针对强类型语言特性,介绍使用%占位符进行类型转换与格式控制(如补零、精度),深入解析Python 2.6+支持的format()方法,涵盖位置参数、关键字参数及字典解包。此外,还讲解了Template类的substitute与safe_substitute用法及其异常处理机制,帮助开发者灵活处理字符串拼接与格式化需求。
本文详细解析Python中实现字符串格式化输出的几种常用方法,供读者参考学习。
Python作为强类型语言,若直接对字符串和数字使用“+”进行拼接,会抛出TypeError错误。Python提供了多种格式化字符串的方式,包括使用占位符、format方法以及自定义模板等。下文将逐一介绍这些方法的具体应用。
以下示例展示了Python作为强类型语言在类型处理上的严格性:
print "abc" + 123 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
因此,在涉及不同类型数据时,必须进行显式的类型转换或格式化输出。
常用占位符格式
| 符号 | 意思 |
| %s | 字符串 |
| %d / %i | 十进制整数 |
| %u | 过时的十进制使用方法 |
| %o | 八进制整数 |
| %x / %X | 十六进制整数 |
| %f / %F | 浮点数 |
| %e / %E | 科学技术法 |
| %% | 输出% |
第一种使用方式
直接调用占位符进行格式化
print '%s+%d' % ('abc', 123) #abc+123
print '%o' % 10 #12 八进制
若需为%d指定宽度,可使用%05d格式。当数字位数不足5位时,左侧自动补0;若数字位数超过指定长度,则按实际长度输出,不受补零限制。
print '%s+%05d' % ('abc', 123) #abc+00123
print '%03x' % 10 #00a
print '%.3e' % 123456789 #1.235e+08 保留3位小数的科学技术法
第二种使用方式
结合字典进行格式化
当需要拼接大量重复元素时,采用上述字典格式化方式较为便捷。
第三种使用方式
采用format方法,该方法自Python 2.6版本起开始支持。
print '{0}{1}{2}{3}'.format('a', 'b', 'c', 123) #abc123
print '{}, {}, {}'.format('a', 'b', 'c') #abc 2.7+ only
print '{2}, {1}, {0}'.format('a', 'b', 'c') #c, b, a
print '{2}, {1}, {0}'.format(*'abc') #c, b, a
print '{0}{1}{0}'.format('abra', 'cad') #abracadabra
通过参数名称进行格式化
print 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') #Coordinates: 37.24N, -115.81W
coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
print 'Coordinates: {latitude}, {longitude}'.format(**coord) #Coordinates: 37.24N, -115.81W
结合元组进行格式化
coord = (3, 5)
print 'X: {0[0]}; Y: {0[1]}'.format(coord) #X: 3; Y: 5
进制转换格式
# format also supports binary numbers
"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42) #'int: 42; hex: 2a; oct: 52; bin: 101010'
3
# with 0x, 0o, or 0b as prefix:
"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42) #'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
数字添加千位分隔符
'{:,}'.format(1234567890) #'1,234,567,890'
百分比格式表示
'{:.2%}'.format(19.5 / 22) # '88.64%'
时间格式化操作
import datetime
today = datetime.datetime.today()
'{:%Y-%m-%d %H:%M:%S}'.format(d) #'2013-09-01 21:10:22'
'{:%Y-%m-%d}'.format(today) #'2013-09-01'
此外,也可使用strftime函数对时间进行格式化。
第四种使用方式
自定义模板字符串
from string import Template
s = Template('$sargs plus $aargs')
s.substitute(sargs = 'abc', aargs = 123) #'abc plus 123'
Template类提供了substitute和safe_substitute两种属性方法。
d = dict(sargs = 'abc') # s.substitute(d) # it's a KeyError s.safe_substitute(d) #'abc plus $aargs'
若未使用safe_substitute且提供的参数不完整,程序将抛出KeyError异常。
更多关于Python相关内容的介绍,请参阅本站专题:《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》。
希望本文所述的Python程序设计内容能对大家有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









