Python format() 関数の使い方
Python の `format()` 関数は文字列の書式設定に使われます。文字列に、変数、定数または式を挿入でき、書式を指定することもできます。`format()` 関数の基本的な使い方は、中かっこ {} に挿入される値の位置を表し、これらの値を文字列に挿入するために `format()` 関数を使用することです。
以下、format() 関数の使用方法の例を説明しています。
- 位置パラメータ:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
私はアリスで、25歳です。
- インデックスによる位置パラメータの指定:
print("My name is {0} and I am {1} years old.".format(name, age))
私はアリス、25歳です。
- キーワード引数
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))
私の名前はボブで、30歳です。
- 書式付きオプションを使用する:
pi = 3.14159
print("The value of pi is {:.2f}".format(pi))
円周率は 3.14 です。
- 索引とフォーマットオプションを使用します
print("My name is {0:10} and I am {1:03d} years old.".format("Alice", 5))
私はアリスです。005才です。
format() はデータ型に応じて自動的にフォーマットのオプションを選択できます。小数点の精度は浮動小数点、整数の基数は整数などに対応しています。format() は複雑な文字列のフォーマットのニーズを満たし、コードの可読性を高めることができます。