Python での文字列の書式設定

完了

テキストを変換したり、照合や検索などの基本的な操作を実行したりするだけでなく、情報を表示するときはテキストの書式を設定することが不可欠です。 Python でテキストの情報を表示する最も簡単な方法は、print() 関数を使用することです。 変数やその他のデータ構造の情報を、print() で使用できる文字列に取得することが重要であることがわかります。

このユニットでは、Python を使用してテキストに変数値を含めるための有効な方法をいくつか学習します。

パーセント記号 (%) の書式設定

文字列内の変数のプレースホルダーは %s です。 文字列の後、別の % 文字を使い、その後に変数名を続けます。 次の例は、% 文字を使って書式設定する方法を示しています。

mass_percentage = "1/6"
print("On the Moon, you would weigh about %s of your weight on Earth." % mass_percentage)

出力: On the Moon, you would weigh about 1/6 of your weight on Earth.

複数の値を使用すると、構文が変わります。これは、渡される変数を囲むためにかっこが必要になるためです。

print("""Both sides of the %s get the same amount of sunlight, but only one side is seen from %s because the %s rotates around its own axis when it orbits %s.""" % ("Moon", "Earth", "Moon", "Earth"))

出力: Both sides of the Moon get the same amount of sunlight, but only one side is seen from Earth because the Moon rotates around its own axis when it orbits Earth.

ヒント

このメソッドは文字列の書式設定にも有効な方法ですが、複数の変数を扱う場合、エラーが発生し、コードのわかりやすさが低下する可能性があります。 この単位で説明する他の 2 つの書式設定オプションのいずれかの方が、この目的には適しています。

format() メソッド

.format() メソッドは、文字列内のプレースホルダーとして中かっこ ({}) を使用し、テキストを置換するために変数の代入を使用します。

mass_percentage = "1/6"
print("On the Moon, you would weigh about {} of your weight on Earth.".format(mass_percentage))

出力: On the Moon, you would weigh about 1/6 of your weight on Earth.

反復変数に何回も代入する必要はなく、代入する必要がある変数が少ないため、冗長さが減ります。

mass_percentage = "1/6"
print("""You are lighter on the {0}, because on the {0} you would weigh about {1} of your weight on Earth.""".format("Moon", mass_percentage))

出力: You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

空の中かっこの代わりに、置換には数値を使用します。 {0} は、最初の (インデックス 0) 引数を .format() に使用することを意味します (この例では Moon)。 {0} を単純に繰り返してもかまいませんが、読みやすさが低下します。 読みやすさを向上させるには、.format() でキーワード引数を使用してから、中かっこ内で同じ引数を参照します。

mass_percentage = "1/6"
print("""You are lighter on the {moon}, because on the {moon} you would weigh about {mass} of your weight on Earth.""".format(moon="Moon", mass=mass_percentage))

出力: You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

f 文字列について

Python バージョン 3.6 以降では、"f 文字列" を使用することができます。 これらの文字列はテンプレートに似ており、コードの変数名が使用されます。 前の例で f 文字列を使用すると、次のようになります。

print(f"On the Moon, you would weigh about {mass_percentage} of your weight on Earth.")

出力: On the Moon, you would weigh about 1/6 of your weight on Earth.

変数は中かっこで囲み、文字列の前に f プレフィックスを使用する "必要があります"。

f 文字列は、他の書式設定オプションより冗長さが少ないだけでなく、中かっこ内で式を使用することができます。 これらの式は、関数でも直接的な操作でもかまいません。 たとえば、1/6 という値を小数点以下 1 桁のパーセンテージとして表したい場合は、round() 関数を直接使用できます。

print(round(100/6, 1))

出力: 16.7

f 文字列を使用すると、事前に変数に値を代入する必要がありません。

print(f"On the Moon, you would weigh about {round(100/6, 1)}% of your weight on Earth.")

出力: On the Moon, you would weigh about 16.7% of your weight on Earth.

式を使用するのに、関数を呼び出す必要はありません。 どのような文字列メソッドも有効です。 たとえば、見出しを作成するために、文字列で特定の大文字と小文字の使い分けを強制できます。

subject = "interesting facts about the moon"
heading = f"{subject.title()}"
print(heading)

出力: Interesting Facts About The Moon