Python 格式化技巧

一杯热水發表於2024-04-18

  收集的一些,格式化輸出技巧,會不定期更新

from datetime import datetime

"""技巧一:數字格式化"""

n1: int = 1000000000
n2: int = 1_000_000_000
print(n1)
print(n2)  # 1000000000

n3: int = 1e9
n4: int = 1e9
n5: float = 1e9
print(n3)  # 1000000000.0
print(n4)  # 1000000000.0
print(n5)  # 1000000000.0

n6: int = 1000000000
print(f"{n6:_}")  # 1_000_000_000
print(f"{n6:,}")  # 1,000,000,000
print(f"{n6:,d}")  # 1,000,000,000

"""技巧二: 字串格式化"""

name: str = "小明"
print(f"{name:>10}")  # 減去自身長度,剩下的使用空格補全
print(f"{name:<10}")  # 左對齊
print(f"{name:10}") # 也是左對齊,預設行為
print(f"{name:^10}")  # 居中
print(f"{name:*^10}")  # ***小明****
print(f"{name:=^10}")  # ===小明====
print(f"{name:>10}:")  #       小明:
print(f"{name:_>10}:")  # ________小明:
print(f"{name:#>10}:")  # ########小明:
print(f"{name:#<10}:")  # 小明########:
print(f"{name:|>10}:")  # ||||||||小明:

"""技巧三: 時間格式化"""

now: datetime = datetime.now()
print(f"{now:%Y-%m-%d %H:%M:%S}")  # 2023-03-20 15:57:00
print(f"{now:%c}")  # Wed Apr 17 22:18:29 2024
print(f"{now:%x}")  # 04/17/24
print(f"{now:%X}")  # 15:57:00
print(f"{now:%a}")  # Wed
print(f"{now:%A}")  # Wednesday
print(f"{now:%b}")  # Apr
print(f"{now:%B}")  # April
print(f"{now:%I%p}")  # 10PM

"""技巧四: 數字格式化"""
n: float = 123.456789
print(f"{n:.2f}")  # 123.46
print(f"{n:.0f}")  # 123
print(round(n, 2))  # 123.46
print(f"{n:,.3f}")  # 123.457
print(f"{n:_.3f}")  # 123.457


"""技巧五: f-sting 格式化"""
a: int = 5
b: int = 10
my_var: str = "hello world"

print(f"a + b = {a + b}") # a + b = 15
print(f"{a + b = }") # a + b = 15
print(f"{a + b*1000 = :,}") # a + b*1000 = 10,005

print(f"{my_var = }") # my_var = 'hello world'

print(f"bool(a) = {bool(a)}") # bool(a) = True
print(f"{bool(a) = }") # bool(a) = True

相關文章