赞
踩
用Python自带的format和str.format可以给整数、浮点数、复数、Decimal数添加千位分隔符。PEP 378标准里有千位分隔符的格式的详细说明。
以下用了两种方案实现:
import locale
# empty string for platform's default settings
locale.setlocale(locale.LC_ALL, '')
print(format(4901711, "n")) # -> 4,901,711
print("{:n}".format(4901711)) # -> 4,901,711
print("{:d}".format(4901711)) # 4901711
from decimal import Decimal
print(format(1234567, ',d'))
print('{:,d}'.format(1234567))
print(format(1234567.89, ',.2f'))
print(format(12345.6 + 8901234.12j, ',f'))
print(format(Decimal('1234567.89'), ',f'))
https://docs.python.org/zh-cn/3/whatsnew/3.1.html?#pep-378-format-specifier-for-thousands-separator
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。