python3中的format函数

format函数常与print()函数结合使用,具备很强的格式化输出能力。

上代码:

通过变量,逗号隔开:

print('{我}今天{action}'.format(我='拦路雨',action ='在写博客'))  # 通过关键字

使用字典传入,在字典前加入**

grade = {'I' : '拦路雨', '状态': '写博客'}
print('{I}比较无聊,在{状态}'.format(**grade))#字典前加上**
通过位置:
print('{1}今天{0}'.format('拦路雨','写博客'))#通过位置Z

文字排版:

print('{1}今天{0}'.format('拦路雨','写博客'))#通过位置Z
print('{:^20}'.format('拦路雨'))#居中 :^ 宽度14
print('{:>20}'.format('拦路雨'))# 右对齐 :> 宽度14
print('{:<20}'.format('拦路雨')) # 左对齐 :< 宽度14
print('{:*<20}'.format('拦路雨')) # :后边可跟填充物,只允许一个字符
print('{:@>20}'.format('拦路雨'))

精度问题:

print('{:.1f}'.format(3.1415926))
print('{:.4f}'.format(3.14))# .后接保留小数点位数

进制转换:

print('{:b}'.format(250)) # 十进制转换成二进制2
print('{:o}'.format(250)) # 十进制 转换成八进制8
print('{:d}'.format(250)) # 十进制 转换成十进制10
print('{:x}'.format(250)) # 十进制 转换成十六进制16

千位分割符:

print('{:,}'.format(100000000))
print('{:,}'.format(235445.234235)) # 只对数字生效 





扫描二维码关注公众号,回复: 1781566 查看本文章



猜你喜欢

转载自blog.csdn.net/lanluyug/article/details/80245220