Festina lente

急がば回れ(ラテン語)。時には寄り道も。

format関数&波括弧

全く網羅性はありませんが、pythonのformat関数を使ったので、そのメモです。
(実行環境は、python 2.7系です)

  • 波括弧{}が1つの場合
>'test {0}'.format('hoge')
'test hoge'

こんな感じで、"format"の引数の文字列'hoge'が{0}に渡されて、最終的に'test hoge'が出力されます。
応用として、引数が2つある場合は、

>'test {0} {1}'.format('hoge', 'momo')
'test hoge momo'

のように、{0}に'hoge'が、{1}に'momo'が代入されるイメージでしょうか。

  • 波括弧{}が2つの場合
>'test {{0}}'.format('hoge')
'test {0}'

このように{{ }}で囲むと、波括弧自体を表示したい場合と解釈されます。formatの引数'hoge'部分は無視されるので注意。

  • 波括弧{}が3つの場合
>'test {{{0}}}'.format('hoge')
'test {hoge}'

'hoge'部分を表示したければ、さらにもう1つ波括弧をつけます。波括弧の中に文字列'hoge'が表示されてますね。

Please refer for more detailed situation as below:

qiita.com

https://docs.python.org/2.7/library/string.html#formatstrings
http://python.civic-apps.com/string-format-function/
http://www.lifewithpython.com/2015/04/python-use-braces-in-string-format.html