python print のオプション(改行したくない場合など)

python Python

既定の動作

Python
print("Hello")
print("World")
# Hello
# World

末尾に\nをつけて改行するのはご存じの通り。

改行したくない場合

Python
print("Hello_", end="")
print("World")
# Hello_World

任意の区切り文字を使う

Python
print("Hello", end=" ")   # スペース
print("World")
# Hello World
print("Hello", end="-") 
print("World")
# Hello-World
print("Loading", end="...")
print("Done")
# Loading...Done

文字列内の任意の場所で強制改行したいとき

Python
print("Hello\nWorld")
# Hello
# World

複数の値をセミコロン区切りで出力

Python
print("A", "B", "C", sep=";")
# A;B;C

for i in range(5):
    print(i, end=" ")
# 0 1 2 3 4

出力先を指定する

出力先は、デフォルトでは標準出力になっていますが、これを特定のファイルや標準エラー出力にすることができます。

Python
# 標準出力への出力(デフォルト動作)
print("This goes to standard output.")

# ファイルへの出力
with open("output.txt", "w") as f:
    print("This goes into a file.", file=f)

# 標準エラー出力へ
print("This is an error message.", file=sys.stderr)

バッファのフラッシュ


flushはブール値(True/False)で、出力ストリームを強制的にフラッシュするかどうかを制御します。デフォルトはFalseです。

通常、print()関数は出力内容を内部のバッファに一時的に保持し、バッファがいっぱいになったときや改行文字が出力されたときなどにまとめて出力します。これはパフォーマンスへの配慮です。

しかし、進行状況の逐次表示、ログの即時書き込みなどリアルタイムでの出力が欲しい場合には、flush=Trueを設定することで、バッファリングをスキップして即座に出力させることができます。

Python
import time

print("Waiting...", end="", flush=False) 
time.sleep(3) 
print("Done!")

このコードを実行すると、flush=True では即座に “Waiting…” を表示しますが、flush=Falseの場合には、3秒後にWaiting…とDone!をまとめて表示します。

コメント

タイトルとURLをコピーしました