Python中的print()
函數(shù)是一個(gè)非常靈活和實(shí)用的工具,可以通過(guò)多種方式進(jìn)行格式化和定制。以下是一些進(jìn)階技巧:
格式化字符串:使用str.format()
或f-string(Python 3.6+)來(lái)格式化輸出。
name = "Alice"
age = 30
# 使用str.format()
print("My name is {} and I am {} years old.".format(name, age))
# 使用f-string
print(f"My name is {name} and I am {age} years old.")
指定輸出寬度:使用width
參數(shù)指定輸出的最小寬度,如果不足則在左側(cè)填充空格。
print("Hello", end="", flush=True)
print("World!")
指定輸出精度:使用precision
參數(shù)指定浮點(diǎn)數(shù)的小數(shù)點(diǎn)后保留的位數(shù)。
pi = 3.141592653589793
print("{:.2f}".format(pi)) # 輸出:3.14
文本對(duì)齊:使用<
、>
、^
分別表示左對(duì)齊、右對(duì)齊、居中對(duì)齊。
print("{:<10}".format("left")) # 輸出:left
print("{:>10}".format("right")) # 輸出: right
print("{:=^10}".format("center")) # 輸出: center
轉(zhuǎn)義字符:使用\
來(lái)轉(zhuǎn)義特殊字符,例如換行符\n
、制表符\t
等。
print("Hello\nWorld!") # 輸出:
# Hello
# World!
分隔符和結(jié)束符:使用sep
和end
參數(shù)自定義分隔符和結(jié)束符。
print(1, 2, 3, sep="-", end="!\n") # 輸出:1-2-3!
輸出到文件:將print()
的輸出重定向到文件。
with open("output.txt", "w") as f:
print("Hello, world!", file=f)
使用顏色:在終端中輸出帶有顏色的文本。
import sys
print("\033[31mRed text\033[0m", file=sys.stderr)
這些只是print()
函數(shù)的一些進(jìn)階技巧,更多高級(jí)功能可以通過(guò)學(xué)習(xí)其他Python庫(kù)(如rich
)來(lái)實(shí)現(xiàn)。