python中format函数的用法

2023-09-25 8 0

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

1. 通过变量,逗号隔开:

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

 输出:

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

grade = {'I' : '脚踏前路', '状态': '写博客'}
print('{I}在图书馆,{状态}'.format(**grade))#字典前加上**

输出:

3.  通过位置:

print('{0}今天{1}'.format('脚踏前路','写博客')) #通过位置

 输出:

4. 文字排版: 

print('{:^20}'.format('脚踏前路'))#居中 :^ 宽度14
print('{:>20}'.format('脚踏前路'))# 右对齐 :> 宽度14
print('{:<20}'.format('脚踏前路')) # 左对齐 :< 宽度14
print('{:*<20}'.format('脚踏前路')) # :后边可跟填充物,只允许一个字符
print('{:*>20}'.format('脚踏前路'))

输出:

 5. 精度问题:

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

输出: 

6. 进制转换:

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

输出:

7. 千位分割符: 

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

 输出:

 

 

代码编程
赞赏

相关文章

阿里云服务器添加安全组
前端选择器的简单介绍
变量、数据类型的简单介绍
和java初识
JavaScript对象以及初识面向对象
第三章 JavaScript操作和DOM对象