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