Python笔记-文本字符串格式化
来源:互联网 发布:ubuntu论坛 编辑:程序博客网 时间:2024/04/29 19:46
文本字符串格式化
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'
0 0
- Python笔记-文本字符串格式化
- python字符串格式化笔记
- python笔记之字符串格式化
- Python学习笔记(2)格式化字符串
- python笔记---字符串格式化函数format
- python学习笔记20(字符串格式化)
- Python学习笔记:字符串格式化方式
- Python字符串格式化符号
- PYTHON 字符串格式化
- 字符串格式化(python)
- Python:字符串格式化
- python字符串格式化
- Python字符串格式化
- Python字符串格式化问题
- python字符串的格式化
- python 格式化字符串
- Python字符串格式化
- python 格式化时间字符串
- 计算最少出列多少位同学,使得剩下的同学排成合唱队形(C++)
- 文章标题
- STL之Vector(Linux内核)完整实现
- 第六章 选择结构程序设计
- P1508 Likecloud-吃、吃、吃
- Python笔记-文本字符串格式化
- 洛谷 3372_【模板】线段树 1_线段树
- hibernate学习(1):hibernate基本架构和关系映射详解
- 网站日志统计案例分析与实现
- 图解.NET Stack和Heap的本质区别
- 在Ubuntu中安装Apache服务器(使用openjdk java)
- 分类算法系列2----逻辑回归Logistic原理和Python实现
- Linux greb
- 求一亿个数字里面最小的10个数字