1
1

More than 1 year has passed since last update.

Pythonの便利技と注意点:format編

Posted at

目次に戻る

format()もしくはf''の技

インデックスは順番になってなくてもよい上、複数回使用可能
>>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
'to be or not to be'
フィールドは番号ではなく名前やインポートした名前でも使用可能
>>> from math import pi
>>> "{name}の値はおよそ{value:.2f}。".format(value=pi, name="π")
'πの値はおよそ3.14。'
無名フィールド、名前フィールドの混在も可能だが、名前フィールドを先に指定するとエラー
>>> "{} {} {} {foo}".format(1, 5, 10, foo=3)
'1 5 10 3'

>>> "{} {} {} {foo}".format(foo=3, 1, 5, 10)
SyntaxError: positional argument follows keyword argument
位置フィールドと名前フィールドの混在も可能
>>> "{hoge} {1} {geho} {0}".format(1, 2, geho=4, hoge=3)
'3 2 4 1'
無名フィールドと位置フィールドを混在させるとエラーになる
>>> "{} {2} {} {3}".format(1, 2, 4, 3)
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    "{} {2} {} {3}".format(1, 2, 4, 3)
ValueError: cannot switch from automatic field numbering to manual field specification
値の一部を使うこともできる
>>> fruits = ["Apple", "Orange"]
>>> "{name[0]}".format(name=fruits)
'Apple'
>>> "{name[1]}".format(name=fruits)
'Orange'
数値の型指定も可能
>>> "Int型:{num}".format(num=15)
'Int型:15'

>>> "Float型:{num:f}".format(num=15)
'Float型:15.000000'

>>> "2進数型:{num:b}".format(num=15)
'2進数型:1111'
変数には日本語も使えて当然計算も可能
>>> from math import pi
>>> 半径 = 3
>>> f'半径{半径}の円の面積は{pi * 半径 * 半径:.2f}です。'
'半径3の円の面積は28.27です。'

目次に戻る

1
1
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
1
1