1.旧式 % 格式化
% 百分号格式化和 C 语言的 printf 格式化差不多。
# '%%' 格式化成 '%'
print('%% %d' % 1) #输出百分号和数字
# %c 字符及其ASCII码
print('%c' % 48) #输出ascii码48对应的0
# %s 字符串
# %d 十进制有符号整数
# %u 十进制无符号正数
# %o 八进制无符号数
# %x 十六进制无符号数
# %X 十六进制无符号数,大写字母
# %e 浮点数科学计数法
# %E 浮点数科学计数法,大写E
# %f 浮点数,小数点表示
print('%f' % 1.1) #输出1.100000默认六位小数
print('%.2f' % 1.1) #指定两位小数
# %g 浮点数,根据值大小采用 %e 或 %f
# %G 参照%g
# %p 十六进制地址
# %n 存储输出字符的数量放进参数列表的下一个变量中
# 多个参数时,可以用括号括起来
print('%d %s' % (999,'yyds'))
# 也可以用字典key来获取对应值
print('%(id)d %(str)s' % {'str':'yyds','id':999})
2.str.format() 方法
后来引入了一个新的字符串格式化的方法,str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。format 接受任意个参数,位置可以不按顺序。
#顺序查找
print('{} and {} and {}'.format(1, 2, 3))
#指定位置
print('{2} and {1} and {0}'.format(1, 2, 3))
#通过参数名
print('{one} and {two} and {three}'.format(one=1,three=3,two=2))
#进行格式化
print('{one:d} and {two:.2f} and {three:s}'.format(one=1,three='three',two=2))
#取单个字符
print('{str[0]}'.format(str='hello world'))
#根据宽度对齐,^、分别是居中、左对齐、右对齐
#全部为10个字符宽度左对齐
print('name={:
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?