pythonの文字列フォーマットの方法はprintf形式とformatメソッドの2種類あります。
printf形式
C言語のprintf形式と同様に%演算子に対し、フォーマットすることができます。
順番にタプルで指定する方法と、辞書でキーを指定する方法があります。
タプル
%sを列挙し、%演算子の後にタプルを指定します。
text = "There are %s, %s and %s." f_text = text % ('apple', 'bananas', 'oranges',) print(f_text) # There are apple, bananas and oranges.
辞書
%とsの間に丸括弧でキーを挟むと、辞書を指定することができます。以下のサンプルは、"first", "second", "third"がそれぞれキーになります。複雑なフォーマットを指定する場合はこちらを使用したほうがよいでしょう。
text = "There are %(first)s, %(second)s and %(third)s." f_text = text % {'first': 'apple', 'second': 'bananas', 'third': 'oranges'} print(f_text) # There are apple, bananas and oranges.
formatメソッド
中括弧で置換フィールドを設定することができます。
text = "There are {0}, {1} and {2}." f_text = text.format('apple', 'bananas', 'oranges', ) print(f_text)