大家在工作的时候经常用到的字符格式化,今天就总结一下:
微信公众号:zeropython
Last login: Wed Jan 9 10:06:43 on ttys000
➜ ~ ipython3 微信公众号:zeropython
Python 3.6.8 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: a = 123
In [2]: b = 1234567890.123456
In [3]: c = -123456.654321
In [4]: type(a)
Out[4]: int
In [5]: type(b)
Out[5]: float
In [9]: "数值{}".format(a)
Out[9]: '数值123'
In [10]: "数值{}".format(b)
Out[10]: '数值1234567890.123456'
# 新增
In [11]: f"数值{a}"
Out[11]: '数值123'
In [9]: "数值{}".format(a)
Out[9]: '数值123'
In [10]: "数值{}".format(b)
Out[10]: '数值1234567890.123456'
In [11]: f"数值{a}"
Out[11]: '数值123'
In [12]: f"数值{b}"
Out[12]: '数值1234567890.123456'
In [13]: # 以浮点型的方式显示呢
In [14]: f"数值{a:f}"
Out[14]: '数值123.000000'
In [15]: "数值{:f}".format(a)
Out[15]: '数值123.000000'
In [16]: # 正负数 显示,整数只能显示整数,负数只显示负数
In [17]: "数值{:+f}".format(a)
Out[17]: '数值+123.000000'
In [18]: "数值{:-f}".format(a)
Out[18]: '数值123.000000'
In [19]: "数值{:+f}".format(c)
Out[19]: '数值-123456.654321'
In [20]: a
Out[20]: 123
In [21]: b
Out[21]: 1234567890.123456
# 如果想三位显示一个逗号进行区分直接在第二个f前面加,
In [23]: f"数值{b:,f}"
Out[23]: '数值1,234,567,890.123456'
# 如果设置保留精度呢?
# .2f 就表示保留两位小数,保留规则为四舍五入
In [26]: f"数值{b:,.2f}"
Out[26]: '数值1,234,567,890.12'
In [27]: f"数值{b:,.3f}"
Out[27]: '数值1,234,567,890.123'
In [28]: f"数值{b:,.4f}"
Out[28]: '数值1,234,567,890.1235'
In [29]: # 如果想以百分比显示呢?
In [30]:
In [30]: x = 10
In [31]: y = 3
In [35]: "百分比{:.2%}".format(x/y)
Out[35]: '百分比333.33%'
是不是 很全面? 更多请关注: