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の文字列補完 (`format` メソッドと `f-strings`)

Posted at

Pythonの文字列補完 (format メソッドと f-strings)

Pythonでは、文字列に変数の値を埋め込む方法として、format メソッドや f-strings が利用できます。これらを使うと、ハードコーディングを避けながら柔軟な文字列操作が可能になります。


1. メソッドとは?

  • 文字列に様々な機能を付与する特定の操作を メソッド と呼びます。
  • format メソッドは、文字列に変数や値を挿入するためのメソッドの一つです。

2. format メソッドの基本

  • format メソッドを使用すると、ハードコーディングを避け、変数の内容を文字列に挿入できます。
hello = "konnnichiwa"
world = "sekai"
print("Message: {} {}".format(hello, world))
出力
Message: konnnichiwa sekai

ポイント: {} の中に、format メソッドで指定した値や変数が挿入されます。


3. format メソッドの応用

  • 複数の変数を指定することも可能です。
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
出力
My name is Alice and I am 25 years old.
  • インデックス番号を指定して値の順序を入れ替えることも可能:
print("{1} and {0}".format("first", "second"))
出力
second and first

4. f-strings

  • Python 3.6以降では、f-strings を使用することで、文字列補完がより簡潔に記述できます。
hello = "konnnichiwa"
world = "sekai"
print(f"{hello} {world}")
出力
konnnichiwa sekai

5. f-strings の応用

  • 変数や式を {} の中に直接記述できます。

例1: 式を埋め込む

x = 10
y = 20
print(f"The sum of x and y is {x + y}")
出力
The sum of x and y is 30

例2: 小数点以下の桁数指定

pi = 3.14159
print(f"Pi rounded to 2 decimal places is {pi:.2f}")
出力
Pi rounded to 2 decimal places is 3.14

ポイント: f-strings は、シンプルで読みやすい記述ができるため、format メソッドよりも推奨されることが多いです。


6. format メソッド vs f-strings

  • format メソッド:
    • どのPythonバージョンでも利用可能。
    • 長い文字列や複雑なフォーマットには便利。
  • f-strings:
    • Python 3.6以降で使用可能。
    • シンプルで直感的な記述が可能。

7. まとめ

  • format メソッドや f-strings を使うと、変数や計算結果を簡単に文字列に挿入できます。
  • f-strings はコードを短く、読みやすくするために推奨されます。
  • プロジェクトに応じて、適切な方法を選びましょう。
0
0
0

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?