python用format格式化数字
格式化输出单个数字的时候,可以使用内置的 format() 函数,比如:
>>> x = 1234.56789 >>> # Two decimal places of accuracy >>> format(x, '0.2f') '1234.57' >>> # Right justified in 10 chars, one-digit accuracy >>> format(x, '>10.1f') ' 1234.6' >>> # Left justified >>> format(x, '<10.1f') '1234.6 ' >>> # Centered >>> format(x, '^10.1f') ' 1234.6 ' >>> # Inclusion of thousands separator >>> format(x, ',') '1,234.56789' >>> format(x, '0,.1f') '1,234.6' >>>
如果你想使用指数记法,将f改成e或者E(取决于指数输出的大小写形式)。比如:
>>> format(x, 'e') '1.234568e+03' >>> format(x, '0.2E') '1.23E+03' >>>
同时指定宽度和精度的一般形式是 ‘[<>^]?width[,]?(.digits)?’ , 其中 width 和 digits 为整数,?代表可选部分。 同样的格式也被用在字符串的 format() 方法中。比如:
>>> 'The value is {:0,.2f}'.format(x) 'The value is 1,234.57' >>>
原文地址:https://www.jianshu.com/p/9813a5cce148
相关推荐
-
Python告警处理 python基础
2019-10-16
-
用Python调教微信,实现自动回复 和 微信好友分布,好友性别图,好友标签 python基础
2019-3-6
-
Python装饰器不会传参?别着急,这篇文章为你解惑 python基础
2020-6-11
-
python自动刷新列车票 python基础
2020-6-17
-
用Python做一个久坐提醒小助手 python基础
2020-6-17
-
【Python教程】08.正则表达式 python基础
2020-6-17
-
『浅入深出』 MySQL 中事务的实现 python基础
2019-8-26
-
Python内核阅读(三): 整型对象 python基础
2019-7-21
-
aliyun域名解析python api python基础
2019-9-11
-
leetcode 11. 盛最多水的容器 – 两种解法 – python python基础
2020-6-17