意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

Python中字符串格式化输出(python中字典的键类型)

来源:恒创科技 编辑:恒创科技编辑部
2023-12-25 13:44:59

Python中字符串格式化有三种方式,分别是 format,% 以及 f (3.7以上版本)。

一. format

格式:'{}'.format()


Python中字符串格式化输出(python中字典的键类型)

1,format()这里括号里写变量名,然后将值按照先后顺序放入打大括号内

代码:

Python中字符串格式化输出_字符串格式化 format % f

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_02

2,加上序号,值不按照先后顺序,按照数字顺序放入大括号内

代码:

Python中字符串格式化输出_字符串格式化 format % f_03

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_04

3,将输出值进行小数保留

代码:

Python中字符串格式化输出_字符串格式化 format % f_05

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_06

4,根据关键字将值放入大括号内输出

代码:

Python中字符串格式化输出_字符串格式化 format % f_07

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_08

二. %

格式:'{}' % 变量名 或者 '{},{}...' % (变量名1,变量名2,...)

1,%s 按字符串类型输出

代码:

Python中字符串格式化输出_字符串格式化 format % f_09

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_10

2,%d

A,%d 按整数型进行输出,如果值是小数会将小数点后的所有数去掉进行输出

代码:

Python中字符串格式化输出_字符串格式化 format % f_11

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_12

B,还有其他情况,比如%.4d或者%04d会打印四位数的整数数字(如果实际数的数不够就会往前面补充0)

代码:

Python中字符串格式化输出_字符串格式化 format % f_13

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_14

3,%f

A,%f 输出浮点数,如果值是整数会将输出浮点数,有小数点

代码:

Python中字符串格式化输出_字符串格式化 format % f_15

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_16

B,限定小数进行输出,比如限定两位小数进行输出

代码:

Python中字符串格式化输出_字符串格式化 format % f_17

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_18

三. f,其实这是format的缩写

格式:f’{}‘

代码:这里就是直接将变量名填入大括号中输出,value4:.3f是保留三位小数输出的意思。

Python中字符串格式化输出_字符串格式化 format % f_19

运行结果:

Python中字符串格式化输出_字符串格式化 format % f_20

最后,%可以与f'{}'一起连用。
















上一篇: Python中多维数组切片如何实现,有几种方法 下一篇: 数据结构课设:图书信息管理--顺序存储和链式存储(数据结构课设图书管理系统)