python格式化输出
来源:互联网 发布:数据恢复大师官网 编辑:程序博客网 时间:2024/06/04 19:13
1、打印字符串
>>> print ("His name is %s"%("Aviad"))His name is Aviad
2.打印整数
>>> print ("He is %d years old"%(25))He is 25 years old
3.打印浮点数
>>> print ("His height is %f m"%(1.83))His height is 1.830000 m
4.打印浮点数(指定保留小数点位数)
>>> print ("His height is %.2f m"%(1.83))His height is 1.83 m
5.指定占位符宽度
>>> print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))Name: Aviad Age: 25 Height: 1.83
6.指定占位符宽度(左对齐)
>>> print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83))Name:Aviad Age:25 Height:1.83
7.指定占位符(只能用0当占位符?)
>>> print ("Name:%-10s Age:%08d Height:%08.2f"%("Aviad",25,1.83))Name:Aviad Age:00000025 Height:00001.83
>>> print("1/3 equal %.3f %%" % (33.33333))1/3 equal 33.333 %
8.%%
>>> print("1/3 equal %.3f %%" % (33.33333))1/3 equal 33.333 %
9.科学计数法
>>> format(0.0015,'.2e')'1.50e-03'
python之字符串格式化(format)
用法: 它通过{}和:来代替传统%方式
1、使用位置参数
要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表
>>> li = ['hoho',18]>>> 'my name is {} ,age {}'.format('hoho',18)'my name is hoho ,age 18'>>> 'my name is {1} ,age {0}'.format(10,'hoho')'my name is hoho ,age 10'>>> 'my name is {1} ,age {0} {1}'.format(10,'hoho')'my name is hoho ,age 10 hoho'>>> 'my name is {} ,age {}'.format(*li)'my name is hoho ,age 18'
2、使用关键字参数
要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可
>>> hash = {'name':'hoho','age':18}>>> 'my name is {name},age is {age}'.format(name='hoho',age=19)'my name is hoho,age is 19'>>> 'my name is {name},age is {age}'.format(**hash)'my name is hoho,age is 18'
3、填充与格式化
:[填充字符][对齐方式 <^>][宽度]
>>> '{0:.2f}'.format(1 / 3)'0.33'>>> '{0:b}'.format(10) #二进制'1010'>>> '{0:o}'.format(10) #八进制'12'>>> '{0:x}'.format(10) #16进制 'a'>>> '{:,}'.format(12369132698) #千分位格式化'12,369,132,698'
4、精度与进制
>>> '{0:.2f}'.format(1/3)'0.33'>>> '{0:b}'.format(10) #二进制'1010'>>> '{0:o}'.format(10) #八进制'12'>>> '{0:x}'.format(10) #16进制'a'>>> '{:,}'.format(12369132698) #千分位格式化'12,369,132,698'
5、使用索引
>>> li['hoho', 18]>>> 'name is {0[0]} age is {0[1]}'.format(li)'name is hoho age is 18
转载自http://www.cnblogs.com/plwang1990/p/3757549.html
0 0
- python中的格式化输出
- python 格式化输出
- python 格式化输出
- python格式化dict输出
- python格式化输出
- python 格式化输出
- Python 的格式化输出
- python 字符串格式化 输出
- Python格式化输出
- Python print 格式化输出
- python 格式化输出
- python 格式化输出
- python格式化输出
- python格式化输出
- python 格式化输出
- Python格式化输出
- [python]格式化输出
- python print格式化输出
- L2-008 最长对称子串
- 设计模式(2):工厂方法模式(Factory Method Pattern)
- 两种常见的UITabBarController+UINavigationController模式
- sql server2012设置用户登陆名字及密码
- nginx简介与安装配置
- python格式化输出
- L1-006. 连续因子
- 第二道算法题
- python调用c/c++
- Android 初学者必学ListView
- 数字系统中的亚稳态及其解决办法
- SpringBoot-从入门到放弃(二) 开发环境的搭建
- c语言排序
- python中numpy中的ndarray方法和属性