2024年7月28日日曜日

Pythonでのトリプルクォーテーションとf文字列の使い方

トリプルクォーテーション

Pythonでは、トリプルクォーテーション (シングルクォーテーション ""' or ダブルクォーテーション """""") を使って、複数行にわたる文字列を記述することができます。これは、改行文字 (\n) を含む長い文字列を定義するのに便利です。

例:

Python
multiline_string = """This is a string
that spans multiple lines.
You can include special characters
like 'quotation marks' and \n newlines."""

print(multiline_ストンリング)

このコードを実行すると、次のように出力されます。

This is a string
that spans multiple lines.
You can include special characters
like 'quotation marks' and 
 newlines.

トリプルクォーテーションを使用すると、コード内の文字列が読みやすくなり、保守性が向上します。

f文字列

f文字列は、Python 3.6以降で導入された新しいタイプの文字列リテラルです。f文字列を使用すると、変数や式などの値を直接文字列の中に埋め込むことができます。

例:

Python
name = "Alice"
age = 30

# 変数を埋め込む
greeting = f"Hello, {name}! You are {age} years old."

# 計算式を埋め込む
pi = 3.14159
area_of_circle = f"The area of a circle with radius 5 is {pi * 5**2:.2f}."

print(greeting)
print(area_of_circle)

このコードを実行すると、次のように出力されます。

Hello, Alice! You are 30 years old.
The area of a circle with radius 5 is 78.54.

f文字列は、文字列の連結やフォーマットを行うよりも、可読性が高く、コードが簡潔になります。

機能説明
トリプルクォーテーション複数行にわたる文字列を記述するためのもの
f文字列変数や式などの値を直接文字列の中に埋め込むためのもの

まとめ

トリプルクォーテーションとf文字列は、どちらもPythonの文字列リテラルを便利にする機能です。トリプルクォーテーションは長い文字列を記述するのに適しており、f文字列は変数や式を文字列の中に埋め込むのに適しています。使い分けることで、コードの可読性と保守性を向上させることができます。

0 件のコメント:

コメントを投稿