0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで文字列を繰り返し*演算子

Posted at

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ツールやログファイルの整形、デバッグ時の視認性向上など、多くの場面で役立ちます。ぜひ試してみてください!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?