8 - 格式化整數和浮點數

整數格式化

  • 請格式化一個整數,按10位輸出,不足10位前面補0
n = 1234

print(format(n, '10d'))
# 左側補零
print(format(n, '0>10d'))
# 右側補零
print(format(n, '0<10d'))
      1234
0000001234
1234000000

浮點數格式化

  • 格式化一個浮點數,要保留小數點兩位
x1 = 1234.5678
x2 = 58.1

# 保留小數點後兩位
print(format(x1, '0.2f'))
print(format(x2, '0.2f'))
1234.57
58.10

3. 請描述format 函數的主要用法

# format 函數用於格式化數值,通過第二個參數指定格式化規則

# 右對齊
print(format(x2, '*>12.2f'))

# 左對齊
print(format(x2, '*<12.2f'))

# 中心對齊
print(format(x2, '*^12.2f'))

# 用千位號分割
print(format(123455678, ','))

# 整數用','分割,並保留小數點後兩位
print(format(123456.12321, ',.2f'))

# 按科學計數法輸出
print(format(x1, 'e'))

# 保留小數點後兩位,科學計數法輸出
print(format(x1, '0.2E'))
*******58.10
58.10*******
***58.10****
123,455,678
123,456.12
1.234568e+03
1.23E+03

9 - python 字符串操作

發佈了128 篇原創文章 · 獲贊 128 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章