Python之数字的格式化输出


需求:

将数字格式化后输出,并控制数字的位数、对齐、千位分隔符和其他的细节
x = 1234.56789
# Two decimal places of accuracy
print(format(x, '0.2f')) # '1234.57'

# Right justified in 10 chars, one-digit accuracy
print(format(x, '>10.1f'))  # '1234.6'

# Left justified
print(format(x, '<10.1f'))  # '1234.6    '

# Centered
print(format(x, '^10.1f'))  # 1234.6

# Inclusion of thousands separator
print(format(x, ','))  # '1,234.56789'
print(format(x, '0,.1f'))  # '1,234.6'
二八十六进制整数
x=1234
print(bin(x))  # 0b10011010010
print(oct(x))  # 0o2322
print(hex(x))  # 0x4d2
# 去掉进制的前缀,可以用format
print(format(x,"b"))  # 10011010010
print(format(x,"o"))  # 2322
print(format(x,"x"))  # 4d2

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM