Pythonでコンソールやログに出力を装飾したいとき、文字列の繰り返し機能を活用すると便利です。
Pythonでの文字列の繰り返し
Pythonでは、文字列に対して*演算子を使うことで簡単に繰り返し文字列を生成できます。
# 基本的な例
line = "=" * 20
print(line)
====================
タイトルを装飾して見やすくする
文字列の繰り返しと文字列の結合(+)を組み合わせることで、簡単にタイトルを装飾できます。
- 基本的なタイトル装飾
以下の例では、左右に「=」を20回繰り返してタイトルを囲んでいます。
title = "Python"
print("=" * 20 + " " + title + " " + "=" * 20)
==================== Python ====================
- f-stringを使った例
Python 3.6以降で利用可能なf-stringを使うと、さらにコードが簡潔になります。
title = "Learn Python"
print(f"{'=' * 20} {title} {'=' * 20}")
==================== Learn Python ====================
応用例:実際のシナリオでの利用
- コマンドラインアプリケーション
def display_section(title):
print("\n" + "=" * 40)
print(f"{title.center(40)}")
print("=" * 40)
display_section("User Information")
========================================
User Information
========================================
- ログファイル
def log_header(title):
header = "=" * 50
with open("log.txt", "a") as log_file:
log_file.write(f"\n{header}\n")
log_file.write(f"{title.center(50)}\n")
log_file.write(f"{header}\n")
log_header("Application Started")
==================================================
Application Started
==================================================
Pythonの文字列の繰り返し機能を活用すると、簡単に見栄えの良い出力を作成できます。CLIツールやログファイルの整形、デバッグ時の視認性向上など、多くの場面で役立ちます。ぜひ試してみてください!