Python笔记-文本字符串格式化
2017-04-14 22:15
573 查看
文本字符串格式化
Python 有两种格式化字符串的方式,旧式和新式。1、使用%的旧式格式化
>>> '%s' % 42 '42' >>> '%d' % 42 '42' >>> '%f' % 7.03 '7.030000' >>> '%e' % 7.03 '7.030000e+00' >>> '%d%%' % 100 '100%' >>> actor = 'Richard Gere' >>> "My wife's favorite actor is %s" % actor "My wife's favorite actor is Richard Gere" >>> cat = 'Chester' >>> weight = 28 >>> "Our cat %s weighs %s pounds" % (cat, weight) 'Our cat Chester weighs 28 pounds'
字符串中出现 % 的次数需要与 % 之后所提供的数据项个数相同。
如果只需插入一个数据,例如前面的 actor, 直接将需要插入的数据置于% 后即可。
如果需要插入多个数据,则需要将它们封装进一个元组,例如上例中的 (cat, weight)。
>>> n = 42 >>> f = 7.03 >>> s = 'string cheese' #设定最小域宽为10个字符,最大字符宽度为4,右对齐 >>> '%10.4d %10.4f %10.4s' % (n, f, s) ' 0042 7.0300 stri'
2、使用{}和format的新式格式化
>>> n = 42 >>> f = 7.03 >>> s = 'string cheese' >>> '{} {} {}'.format(f, n, s) '7.03 42 string cheese' >>> '{2} {0} {1}'.format(f, s, n) '42 7.03 string cheese' >>> '{n} {f} {s}'.format(n=42, f=7.03, s='string cheese') '42 7.03 string cheese'
旧式格式化允许在 % 后指定参数格式,但在新式格式化里,将这些格式标识符放在 : 后
>>> n = 42 >>> f = 7.03 >>> s = 'string cheese' >>> '{0:d} {1:f} {2:s}'.format(n, f, s) '42 7.030000 string cheese' >>> '{n:d} {f:f} {s:s}'.format(n=42, f=7.03, s='string cheese') '42 7.030000 string cheese' #最小域宽设为10。 <:右对齐 >:左对齐 ^:居中 >>> '{0:>10d} {1:>10f} {2:>10s}'.format(n, f, s) ' 42 7.030000 string cheese'
3、对于浮点数而言精度仍然代表着小数点后的数字个数, 对于字符串而言精度则代表着最大字符个数,但在新式格式化中你无法对整数设定精度:
>>> '{0:>10.4d} {1:>10.4f} {2:10.4s}'.format(n, f, s) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Precision not allowed in integer format specifier >>> '{0:>10d} {1:>10.4f} {2:>10.4s}'.format(n, f, s) ' 42 7.0300 stri'
相关文章推荐
- Python笔记:加减乘除,格式化字符串
- python字符串格式化笔记
- python笔记之字符串格式化
- python基本数据类型(三)-字符串拼接-格式化输出-深浅复制-python3笔记
- python字符串格式化之学习笔记
- Python笔记 - 字符串_格式化
- python笔记---字符串格式化函数format
- python 字符串&格式化-----廖雪峰教程学习笔记
- devi into python 笔记(七)locals与globals 字典格式化字符串 字符集
- Python 学习笔记 - 字符串的格式化
- python学习笔记20(字符串格式化)
- Python学习笔记-Python的字符串,格式化,条件判断,循环、raw_input的注意事项
- 【零基础入门学习Python笔记015】字符串:格式化
- python字符串格式化笔记
- python字符串格式化之学习笔记
- 小甲鱼Python教程第15讲--python字符串格式化笔记及习题答案
- python学习笔记20(字符串格式化)
- Python学习笔记:字符串格式化方式
- python笔记4 - 索引,切片,字符编码转换函数,字符串的属性方法,字符串格式化表达式,占位符,基于字典的字符串格式化,循环语句