首页 > 编程语言 > 详细

Python %和format的用法

时间:2020-07-10 12:23:53      阅读:67      评论:0      收藏:0      [点我收藏+]

一、%的用法

1.整数的输出

#八进制oct   %o
print(%o % 10)  #12

#十进制dec  %d
print(%d % 1)  #10

#十六进制hex  %x
print(%x % 1)  #a

2.浮点型数据输出

# %f 默认保留6位小数  %.1f 保留1位小数
print(%f,%.1f % (1.11,1.11))  #1.110000,1.1

#%e  默认保留6位小数,用科学计算法 ,%.1保留1位小数
print(%e,%.1e % (1.11,1.11))  #1.110000e+00,1.1e+00

#%g 在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
print(%g,%.1g % (1.1111111,1.1111))  #1.11111,1
print(%g,%.1g % (11111111.1,11111111))  #1.11111e+07,1e+07

3.字符串输出

#%s字符串输出
print(%s % hi)  #hi

#%ns  右对齐,n位占位符,不够则补位
print(%10s % hi,hi,hi)  #  hi,hi,hi

#%-ns  左对齐,n位占位符,不够则补位
print(%-10s % hi,hi,hi)  #hi,hi,hi 
print(%-10s % hi,hi,hi,hi,hi)  #hi,hi,hi,hi,hi

#%.ns  截取n个字符串
print(%.2s % hi,hi,hi)  #hi

#%n.ns  整数部分是占位符,小数点是截取n个字符串
print(%10.2s % hi,hi,hi)  #        hi

4.format用法

该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符

#‘{}’ 最简单格式
print({},{}.format(hello,world))  #hello,world

#位置编号
print({0},{1}.format(hello,world))
print({0},{1},{0}.format(hello,world))  #位置编号,可以输出多次  hello,world,hello
print({1},{1}.format(hello,world))  #world,world

#关键词
print({a},{b}.format(a=hello,b=world))  #a,b关键词 hello,world

 较常用的百分比%输出和会计千分位额输出法

print({:.2%}.format(0.12354))   #百分比
print({:,}.format(123456789))   #会计千位分隔符
print({:.2f}.format(31.31412))  #保留2位小数 
#list映射
l=list(abcd)
print({0[0]},{0[1]},{0[2]},{0[3]}.format(l))

 

Python %和format的用法

原文:https://www.cnblogs.com/cgmcoding/p/13278298.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!