Python の print 関数で出力を配置する方法

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

Python プログラムを書く際に、出力をきれいかつ整理された形式で表示することは、コードの可読性とユーザー体験の両方にとって不可欠です。レポートを作成する場合、表形式のデータを表示する場合、あるいは単にコンソールに情報を印刷する場合でも、適切なテキストの配置により、出力がよりプロフェッショナルで読みやすくなります。

この実験では、Python でテキスト出力を配置し、書式設定するさまざまな手法を学びます。異なる配置方法を探索し、書式設定技術を練習し、実際のアプリケーションに適用できる構造的な表形式の表示を作成します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/list_comprehensions("List Comprehensions") subgraph Lab Skills python/strings -.-> lab-418802{{"Python の print 関数で出力を配置する方法"}} python/conditional_statements -.-> lab-418802{{"Python の print 関数で出力を配置する方法"}} python/list_comprehensions -.-> lab-418802{{"Python の print 関数で出力を配置する方法"}} end

Python での基本的な文字列配置

この最初のステップでは、Python でのテキスト配置の基本概念について学び、基本的な配置手法を実装します。

テキスト配置とは何か?

テキスト配置とは、与えられたスペース内でテキストがどのように配置されるかを指します。Python は、コンソールに印刷する際のテキストの配置を制御するいくつかのメソッドを提供しています。主な配置のタイプは 3 つあります。

  • 左配置:テキストは割り当てられたスペースの左側から始まります。
  • 右配置:テキストは割り当てられたスペースの右側で終わります。
  • 中央配置:テキストは割り当てられたスペース内で中央に配置されます。

最初の配置プログラム

基本的な配置手法を示す簡単な Python スクリプトを作成しましょう。

  1. LabEx 環境の WebIDE を開きます。

  2. WebIDE の「New File」アイコンをクリックして、/home/labex/project ディレクトリに basic_alignment.py という名前の新しいファイルを作成します。

  3. 以下のコードをファイルに追加します。

## basic_alignment.py
print("Basic String Alignment Examples")
print("-" * 30)

## Left alignment example
print("Left alignment:")
print("Python".ljust(20) + "|")
print("Programming".ljust(20) + "|")
print("Alignment".ljust(20) + "|")
print()

## Right alignment example
print("Right alignment:")
print("Python".rjust(20) + "|")
print("Programming".rjust(20) + "|")
print("Alignment".rjust(20) + "|")
print()

## Center alignment example
print("Center alignment:")
print("Python".center(20) + "|")
print("Programming".center(20) + "|")
print("Alignment".center(20) + "|")
  1. Ctrl+S を押すか、メニューから「File」>「Save」を選択してファイルを保存します。

  2. WebIDE でターミナルが開いていない場合は、「Terminal」メニューをクリックして「New Terminal」を選択してターミナルを開きます。

  3. Python インタープリタを使用してスクリプトを実行します。

cd ~/project
python3 basic_alignment.py
  1. 以下のような出力が表示されるはずです。
Basic String Alignment Examples
------------------------------
Left alignment:
Python              |
Programming         |
Alignment           |

Right alignment:
              Python|
         Programming|
           Alignment|

Center alignment:
       Python       |
     Programming    |
      Alignment     |

コードの理解

さっき作成したスクリプトは、Python での 3 つの基本的な文字列配置メソッドを示しています。

  • ljust(width):指定された幅のフィールド内で文字列を左寄せにします。
  • rjust(width):指定された幅のフィールド内で文字列を右寄せにします。
  • center(width):指定された幅のフィールド内で文字列を中央寄せにします。

各例では、割り当てられたスペースの境界を明確に示すために、各行の末尾に縦棒 (|) を追加しています。文字数の合計が 20 文字で同じままで、それぞれの場合でテキストの配置がどのように異なるかに注目してください。

異なる文字での文字列配置

文字列の寄せメソッドは、パディングに使用する埋め文字を指定するための 2 番目のパラメータを取ることもできます。これを実際に確認するために、スクリプトを変更しましょう。

  1. /home/labex/project ディレクトリに alignment_with_chars.py という名前の新しいファイルを作成します。

  2. 以下のコードをファイルに追加します。

## alignment_with_chars.py
print("String Alignment With Custom Characters")
print("-" * 40)

## Using different padding characters
print("Left alignment with dots:")
print("Python".ljust(20, '.') + "|")
print("Programming".ljust(20, '.') + "|")
print()

print("Right alignment with asterisks:")
print("Python".rjust(20, '*') + "|")
print("Programming".rjust(20, '*') + "|")
print()

print("Center alignment with hyphens:")
print("Python".center(20, '-') + "|")
print("Programming".center(20, '-') + "|")
  1. ファイルを保存して実行します。
python3 ~/project/alignment_with_chars.py
  1. 以下のような出力が表示されるはずです。
String Alignment Custom Custom Characters
----------------
Left alignment with dots:
Python..............|
Programming.........|

Right alignment with asterisks:
**************Python|
*********Programming|

Center alignment with hyphens:
-------Python------|
----Programming----|

これらの例は、異なるパディング文字を使用することで、配置されたテキストの外観をカスタマイズできることを示しています。

配置用の高度な書式設定方法

前のステップでは、ljust()rjust()center() メソッドを使った基本的な文字列配置について学びました。今度は、Python で利用可能なより強力で柔軟な書式設定方法を探ってみましょう。

Python の文字列書式設定方法

Python は文字列の書式設定にいくつかの方法を提供しています。

  1. 旧式の書式設定% 演算子を使用)
  2. str.format() メソッド
  3. F 文字列(書式付き文字列リテラル、Python 3.6 以降で利用可能)

各方法は、テキストを配置し、さまざまなデータ型を書式設定する方法を提供します。それぞれを順番に見ていきましょう。

1. 旧式の書式設定(% 演算子)

これは Python で最も古い文字列書式設定方法で、C 言語の printf() 関数に似ています。

  1. /home/labex/project ディレクトリに old_style_formatting.py という名前の新しいファイルを作成します。
## old_style_formatting.py
print("Old-style String Formatting")
print("-" * 30)

## Left alignment with % formatting
print("Left aligned:")
print("%-15s | %-10s" % ("Python", "Language"))
print("%-15s | %-10s" % ("JavaScript", "Web"))
print()

## Right alignment with % formatting
print("Right aligned:")
print("%15s | %10s" % ("Python", "Language"))
print("%15s | %10s" % ("JavaScript", "Web"))
print()

## Numbers formatting
print("Number formatting:")
price = 125.5
tax_rate = 0.21
print("Price: $%8.2f" % price)
print("Tax rate: %6.1f%%" % (tax_rate * 100))
print("Tax amount: $%6.2f" % (price * tax_rate))
print("Total: $%8.2f" % (price * (1 + tax_rate)))
  1. ファイルを保存して実行します。
python3 ~/project/old_style_formatting.py
  1. 以下のような出力が表示されるはずです。
Old-style String Formatting
------------------------------
Left aligned:
Python          | Language
JavaScript      | Web

Right aligned:
         Python |  Language
     JavaScript |       Web

Number formatting:
Price: $   125.50
Tax rate:   21.0%
Tax amount: $ 26.36
Total: $   151.86

2. str.format() メソッド

str.format() メソッドは、文字列の書式設定をより汎用的に行う方法を提供し、% 演算子のいくつかの制限を解消するために導入されました。

  1. /home/labex/project ディレクトリに format_method.py という名前の新しいファイルを作成します。
## format_method.py
print("String Formatting with str.format()")
print("-" * 35)

## Basic alignment with format
print("Basic alignment:")
print("{:<15} | {:<10}".format("Python", "Language"))
print("{:>15} | {:>10}".format("Python", "Language"))
print("{:^15} | {:^10}".format("Python", "Language"))
print()

## Alignment with custom fill character
print("Custom fill character:")
print("{:*<15} | {:.>10}".format("Python", "Language"))
print("{:#^15} | {:=^10}".format("Python", "Language"))
print()

## Alignment with field names
print("Using field names:")
print("{name:<15} | {type:<10}".format(name="JavaScript", type="Web"))
print("{name:>15} | {type:>10}".format(name="Python", type="Language"))
print()

## Number formatting
price = 125.5
tax_rate = 0.21
print("Number formatting:")
print("Price: ${:8.2f}".format(price))
print("Tax rate: {:6.1f}%".format(tax_rate * 100))
print("Tax amount: ${:6.2f}".format(price * tax_rate))
print("Total: ${:8.2f}".format(price * (1 + tax_rate)))
  1. ファイルを保存して実行します。
python3 ~/project/format_method.py
  1. 以下のような出力が表示されるはずです。
String Formatting with str.format()
-----------------------------------
Basic alignment:
Python          | Language
         Python |   Language
    Python      |  Language

Custom fill character:
Python********* | Language...
#####Python##### | ==Language==

Using field names:
JavaScript      | Web
         Python |  Language

Number formatting:
Price: $  125.50
Tax rate:   21.0%
Tax amount: $ 26.36
Total: $  151.86

3. F 文字列(Python 3.6 以降)

F 文字列は、文字列リテラル内に式を埋め込む簡潔で便利な方法を提供します。先頭に 'f' が付き、中括弧 {} を使って式を含めます。

  1. /home/labex/project ディレクトリに f_strings.py という名前の新しいファイルを作成します。
## f_strings.py
print("String Formatting with F-strings")
print("-" * 35)

language = "Python"
category = "Language"
version = 3.10
year = 2022

## Basic alignment with f-strings
print("Basic alignment:")
print(f"{language:<15} | {category:<10}")
print(f"{language:>15} | {category:>10}")
print(f"{language:^15} | {category:^10}")
print()

## Dynamic width specification
width1 = 15
width2 = 10
print("Dynamic width:")
print(f"{language:<{width1}} | {category:<{width2}}")
print(f"{language:>{width1}} | {category:>{width2}}")
print()

## Expressions inside f-strings
print("Expressions in f-strings:")
print(f"{'Python ' + str(version):<15} | {year - 1991:>10} years old")
print()

## Number formatting
price = 125.5
tax_rate = 0.21
print("Number formatting:")
print(f"Price: ${price:8.2f}")
print(f"Tax rate: {tax_rate * 100:6.1f}%")
print(f"Tax amount: ${price * tax_rate:6.2f}")
print(f"Total: ${price * (1 + tax_rate):8.2f}")
  1. ファイルを保存して実行します。
python3 ~/project/f_strings.py
  1. 以下のような出力が表示されるはずです。
String Formatting with F-strings
-----------------------------------
Basic alignment:
Python          | Language
         Python |  Language
    Python      | Language

Dynamic width:
Python          | Language
         Python |  Language

Expressions in f-strings:
Python 3.1      |         31 years old

Number formatting:
Price: $  125.50
Tax rate:   21.0%
Tax amount: $ 26.36
Total: $  151.86

書式設定方法の比較

各書式設定方法にはそれぞれの利点があります。以下はそれぞれの方法を使うタイミングです。

  • % 演算子:レガシーコードで、または古い Python バージョンとの互換性が必要な場合に使用します。
  • str.format()% 書式設定よりも強力で、特に複雑な書式設定要件に適しています。
  • F 文字列:最も簡潔で読みやすいオプションで、すべての新しい Python コード(Python 3.6 以降)で推奨されます。

Python の最新のトレンドは、読みやすさとパフォーマンスの利点から、可能な限り F 文字列を使用することです。

Python で書式付きテーブルを作成する

これまでにさまざまな配置技術を学んだので、それらを応用して書式の整ったテーブルを作成しましょう。テーブルは構造化されたデータを読みやすい形式で表示する一般的な方法であり、適切な配置は表形式の情報を効果的に提示するために重要です。

固定幅列を持つシンプルなテーブル

まずは固定幅列を使ってシンプルなテーブルを作成しましょう。

  1. /home/labex/project ディレクトリに simple_table.py という名前の新しいファイルを作成します。
## simple_table.py
print("Simple Fixed-Width Table")
print("-" * 50)

## Define some data
header = ["Name", "Age", "City", "Profession"]
data = [
    ["John Smith", 34, "New York", "Doctor"],
    ["Sarah Johnson", 28, "San Francisco", "Engineer"],
    ["Michael Brown", 42, "Chicago", "Teacher"],
    ["Emily Davis", 31, "Boston", "Scientist"]
]

## Print header
print(f"{header[0]:<20} {header[1]:<8} {header[2]:<15} {header[3]:<15}")
print("-" * 60)

## Print rows
for row in data:
    print(f"{row[0]:<20} {row[1]:<8} {row[2]:<15} {row[3]:<15}")
  1. ファイルを保存して実行します。
python3 ~/project/simple_table.py
  1. 以下のように書式の整ったテーブルが表示されるはずです。
Simple Fixed-Width Table
--------------------------------------------------
Name                 Age      City            Profession
------------------------------------------------------------
John Smith           34       New York        Doctor
Sarah Johnson        28       San Francisco   Engineer
Michael Brown        42       Chicago         Teacher
Emily Davis          31       Boston          Scientist

複数の配置タイプを持つ動的なテーブル

異なるタイプのデータは、異なる配置スタイルで表示すると見栄えが良くなることが多いです。たとえば、テキストは左寄せ、数値は右寄せにすることが一般的です。混合配置を持つより洗練されたテーブルを作成しましょう。

  1. /home/labex/project ディレクトリに dynamic_table.py という名前の新しいファイルを作成します。
## dynamic_table.py
print("Dynamic Table with Mixed Alignment")
print("-" * 50)

## Define some data
header = ["Product", "Price", "Quantity", "Total"]
products = [
    ["Laptop", 1299.99, 3, 3899.97],
    ["Mouse", 24.50, 10, 245.00],
    ["Monitor", 349.95, 2, 699.90],
    ["Keyboard", 49.99, 5, 249.95],
    ["Headphones", 89.95, 4, 359.80]
]

## Calculate column widths based on content
col_widths = [
    max(len(str(header[0])), max(len(str(row[0])) for row in products)) + 2,
    max(len(str(header[1])), max(len(f"${row[1]:.2f}") for row in products)) + 2,
    max(len(str(header[2])), max(len(str(row[2])) for row in products)) + 2,
    max(len(str(header[3])), max(len(f"${row[3]:.2f}") for row in products)) + 2
]

## Print header
print(f"{header[0]:<{col_widths[0]}}"
      f"{header[1]:>{col_widths[1]}}"
      f"{header[2]:>{col_widths[2]}}"
      f"{header[3]:>{col_widths[3]}}")
print("-" * sum(col_widths))

## Print rows with appropriate alignment
for product in products:
    print(f"{product[0]:<{col_widths[0]}}"
          f"${product[1]:.2f}:>{col_widths[1] - 1}"
          f"{product[2]:>{col_widths[2]}}"
          f"${product[3]:.2f}:>{col_widths[3] - 1}")

## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * sum(col_widths))
print(f"{'TOTAL':<{col_widths[0]}}"
      f"{'':{col_widths[1]}}"
      f"{total_quantity:>{col_widths[2]}}"
      f"${total_cost:.2f}:>{col_widths[3] - 1}")
  1. このコードには修正が必要なエラーがあります。価格と合計の列の書式設定が正しくありません。修正しましょう。
## dynamic_table.py - corrected version
print("Dynamic Table with Mixed Alignment")
print("-" * 50)

## Define some data
header = ["Product", "Price", "Quantity", "Total"]
products = [
    ["Laptop", 1299.99, 3, 3899.97],
    ["Mouse", 24.50, 10, 245.00],
    ["Monitor", 349.95, 2, 699.90],
    ["Keyboard", 49.99, 5, 249.95],
    ["Headphones", 89.95, 4, 359.80]
]

## Calculate column widths based on content
col_widths = [
    max(len(str(header[0])), max(len(str(row[0])) for row in products)) + 2,
    max(len(str(header[1])), max(len(f"${row[1]:.2f}") for row in products)) + 2,
    max(len(str(header[2])), max(len(str(row[2])) for row in products)) + 2,
    max(len(str(header[3])), max(len(f"${row[3]:.2f}") for row in products)) + 2
]

## Print header
print(f"{header[0]:<{col_widths[0]}}"
      f"{header[1]:>{col_widths[1]}}"
      f"{header[2]:>{col_widths[2]}}"
      f"{header[3]:>{col_widths[3]}}")
print("-" * sum(col_widths))

## Print rows with appropriate alignment
for product in products:
    print(f"{product[0]:<{col_widths[0]}}"
          f"${product[1]:.2f}".rjust(col_widths[1])
          f"{product[2]}".rjust(col_widths[2])
          f"${product[3]:.2f}".rjust(col_widths[3]))

## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * sum(col_widths))
print(f"{'TOTAL':<{col_widths[0]}}"
      f"".rjust(col_widths[1])
      f"{total_quantity}".rjust(col_widths[2])
      f"${total_cost:.2f}".rjust(col_widths[3]))
  1. 修正したファイルを保存して実行します。
python3 ~/project/dynamic_table.py
  1. この例を簡素化して、初心者にも分かりやすく、堅牢なものにしましょう。
## dynamic_table.py - simplified version
print("Dynamic Table with Mixed Alignment")
print("-" * 50)

## Define some data
header = ["Product", "Price ($)", "Quantity", "Total ($)"]
products = [
    ["Laptop", 1299.99, 3, 3899.97],
    ["Mouse", 24.50, 10, 245.00],
    ["Monitor", 349.95, 2, 699.90],
    ["Keyboard", 49.99, 5, 249.95],
    ["Headphones", 89.95, 4, 359.80]
]

## Fixed column widths
product_width = 15
price_width = 12
quantity_width = 10
total_width = 12

## Print header
print(f"{header[0]:<{product_width}}"
      f"{header[1]:>{price_width}}"
      f"{header[2]:>{quantity_width}}"
      f"{header[3]:>{total_width}}")
print("-" * (product_width + price_width + quantity_width + total_width))

## Print rows with appropriate alignment
for product in products:
    print(f"{product[0]:<{product_width}}"
          f"{product[1]:>{price_width}.2f}"
          f"{product[2]:>{quantity_width}}"
          f"{product[3]:>{total_width}.2f}")

## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * (product_width + price_width + quantity_width + total_width))
print(f"{'TOTAL':<{product_width}}"
      f"{'':{price_width}}"
      f"{total_quantity:>{quantity_width}}"
      f"{total_cost:>{total_width}.2f}")
  1. この簡素化したバージョンで前のファイルを上書き保存して実行します。
python3 ~/project/dynamic_table.py
  1. 以下のように書式の整ったテーブルが表示されるはずです。
Dynamic Table with Mixed Alignment
--------------------------------------------------
Product            Price ($)  Quantity   Total ($)
-------------------------------------------------------
Laptop              1299.99         3     3899.97
Mouse                 24.50        10      245.00
Monitor              349.95         2      699.90
Keyboard              49.99         5      249.95
Headphones            89.95         4      359.80
-------------------------------------------------------
TOTAL                                24     5454.62

財務レポートの作成

次に、より実用的な例として、配置技術を使って読みやすくした財務レポートを作成しましょう。

  1. /home/labex/project ディレクトリに financial_report.py という名前の新しいファイルを作成します。
## financial_report.py
print("Monthly Financial Report")
print("=" * 60)

## Financial data
income_sources = [
    ["Salary", 5000.00],
    ["Freelance Work", 1200.50],
    ["Investments", 450.75],
    ["Other Income", 300.00]
]

expenses = [
    ["Rent", 1500.00],
    ["Utilities", 250.30],
    ["Groceries", 600.45],
    ["Transportation", 200.00],
    ["Insurance", 300.00],
    ["Entertainment", 150.25],
    ["Savings", 800.00],
    ["Miscellaneous", 300.00]
]

## Print Income Section
print("\nINCOME STATEMENT")
print("-" * 40)
print(f"{'Source':<20}{'Amount ($)':>20}")
print("-" * 40)

total_income = 0
for source, amount in income_sources:
    total_income += amount
    print(f"{source:<20}{amount:>20.2f}")

print("-" * 40)
print(f"{'Total Income':<20}{total_income:>20.2f}")
print()

## Print Expense Section
print("\nEXPENSE STATEMENT")
print("-" * 40)
print(f"{'Category':<20}{'Amount ($)':>20}")
print("-" * 40)

total_expenses = 0
for category, amount in expenses:
    total_expenses += amount
    print(f"{category:<20}{amount:>20.2f}")

print("-" * 40)
print(f"{'Total Expenses':<20}{total_expenses:>20.2f}")
print()

## Print Summary
print("\nMONTHLY SUMMARY")
print("-" * 40)
print(f"{'Total Income':<20}{total_income:>20.2f}")
print(f"{'Total Expenses':<20}{total_expenses:>20.2f}")
print("-" * 40)
balance = total_income - total_expenses
print(f"{'Net Balance':<20}{balance:>20.2f}")

## Add some conditional formatting for the balance
if balance > 0:
    print(f"\nStatus: You saved ${balance:.2f} this month!")
else:
    print(f"\nStatus: You overspent by ${-balance:.2f} this month.")
  1. ファイルを保存して実行します。
python3 ~/project/financial_report.py
  1. 列がきれいに配置された包括的な財務レポートが表示されるはずです。
Monthly Financial Report
============================================================

INCOME STATEMENT
----------------------------------------
Source              Amount ($)
----------------------------------------
Salary                  5000.00
Freelance Work          1200.50
Investments              450.75
Other Income             300.00
----------------------------------------
Total Income            6951.25


EXPENSE STATEMENT
----------------------------------------
Category            Amount ($)
----------------------------------------
Rent                    1500.00
Utilities                250.30
Groceries                600.45
Transportation           200.00
Insurance                300.00
Entertainment            150.25
Savings                  800.00
Miscellaneous            300.00
----------------------------------------
Total Expenses          4101.00


MONTHLY SUMMARY
----------------------------------------
Total Income            6951.25
Total Expenses          4101.00
----------------------------------------
Net Balance             2850.25

Status: You saved $2850.25 this month!

この例は、適切な配置が複雑な財務情報を読みやすく理解しやすくすることができることを示しています。

要点

これらの例を通じて、以下のことを学びました。

  1. 一貫した配置でシンプルな固定幅テーブルを作成する
  2. データ型に基づいて異なる配置タイプを適用する(テキストは左寄せ、数値は右寄せ)
  3. 視覚的に整理された実用的なレポートを作成する
  4. 文字列書式設定方法を使って出力を精密に制御する

これらのスキルはコンソール出力だけでなく、レポートの生成、ログファイルの作成、またはテキストベースの形式でデータを提示する際にも応用できます。

まとめ

この実験では、Python でテキスト出力を配置および書式設定するためのさまざまな技術を学びました。

  • 基本的な文字列配置メソッド:ljust()rjust()center()
  • 異なる文字列書式設定アプローチ:% 演算子、str.format()、および f 文字列
  • 固定幅列を持つ構造化されたテーブルを作成する方法
  • データ型に基づいて異なる配置スタイルを適用する方法
  • 適切な書式設定で財務レポートなどの実用的なアプリケーションを作成する方法

これらのテキスト配置スキルは、シンプルなコマンドラインユーティリティから複雑なデータ処理システムまで、多くのアプリケーションで読みやすいプロフェッショナルな出力を作成するために不可欠です。Python でのテキスト配置を習得することで、プログラムのユーザー体験と読みやすさを大幅に向上させることができます。

Python の学習を続ける際には、クリーンで書式の整った出力は、プログラムの計算ロジックと同じくらい重要であることを忘れないでください。この実験で学んだ技術は、データを機能的で視覚的に魅力的な方法で提示するのに役立ちます。