dackdive's blog

新米webエンジニアによる技術ブログ。JavaScript(React), Salesforce, Python など

[python]文字列置換(フォーマット)まとめ(format関数, %dなど)

python による文字列置換の書き方について。
いくつかあるのでまとめてみました。
python は2.7。

色々調べましたが、公式ドキュメントが一番詳しかった気がします。
(文中にリンクあり。または「リファレンス」参照)

ここから中身。
まず、文字列のフォーマットにはざっくりと以下の2つの方法があります。

  1. %d, %sなどの%演算子のフォーマット
  2. format() 関数を使ったフォーマット

2は python2.6 から導入された新しい関数です。

1. %演算子のフォーマット

参考: http://docs.python.jp/2/library/stdtypes.html#string-formatting

基本的な書き方

# 基本形
>>> print 'Hello, %s!' % 'World'
Hello, World!
# 複数ある場合はタプルで渡す
>>> print 'Hi, %s. You are %d years old' % ('John', 25)
Hi, John. You are 25 years old

文字列内で %s などとし、% で続いて変換したい値を後ろに記述します。
C言語printf() 関数とかと同じですね。

また、桁数などのフォーマットを指定できる他、dict 型で渡すこともできます。

>>> print '%(language)s has %(number)03d quote types.' % {'language': 'Python', 'number': 2}
Python has 002 quote types.

# または、1行が長くなるので一旦変数に入れてからでも

>>> a = {'language': 'Java', 'number': 1}
>>> print '%(language)s has %(number)03d quote types.' % a
Java has 001 quote types.

へー。

代表的な変換型 (%◯)

よく見るものだけメモ。

変換 意味
%d 符号つき 10 進整数
%e, %E 指数表記の浮動小数点数
%r 文字列(Python オブジェクトを repr() で変換したもの)
%s 文字列(Python オブジェクトを str() で変換したもの)



2. format() 関数を使ったフォーマット

参考: http://docs.python.jp/2/library/string.html#formatstrings

基本形

format() 関数を使った場合、上記の一番最初の文は次のような書き方になります。

>>> print 'Hello, {}!'.format('World')
Hello, World!

こちらの場合はもうちょっと色々な指定のオプションがあります。

ポジション引数(インデックス)を使う

{} 内にインデックスを指定することで、渡した順番と表示に使用する順番を対応づけることができます。

>>> print '{0}, {2}, {1}'.format('a', 'b', 'c')
a, c, b

# あるいは、インデックスを繰り返すことで引数を再利用できる
>>> print '{0}, {1}, {0}'.format('a', 'b')
a, b, a

キーワード引数を使う

>>> print '{language} has {number} quote types.'.format(language='Python', number=2)
Python has 2 quote types.

こちらも、引数にdict型を使うことができますが ** でアンパックして渡す必要があります。

>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

# ** をつけないとエラー
>>> 'Coordinates: {latitude}, {longitude}'.format(coord)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'latitude'

クラスの属性にアクセスする

個人的にはこれが一番びっくり。こんな書き方もできます。

>>> class Coord(object):
...     def __init__(self, lat, lon):
...         self.lat, self.lon = lat, lon
...
>>> coord = Coord('37.24N', '-115.81W')
>>> 'Coordinates: {0.lat}, {0.lon}'.format(coord)
'Coordinates: 37.24N, -115.81W'

タプル、リストでも

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

その他

あとは、format() でも桁数指定したりできます。
ここでは省略しますが、公式のサンプルに色々書いてます。

http://docs.python.jp/2/library/string.html#formatexamples

リファレンス

format()関数について
http://docs.python.jp/2/library/string.html#formatstrings

と、サンプル
http://docs.python.jp/2/library/string.html#formatexamples

%演算子について
http://docs.python.jp/2/library/stdtypes.html#string-formatting

あとは、こちらの記事が非常に参考になりました。

format関数による文字列フォーマット(新しい形式 / 3.6対応) | Python Snippets

文字列フォーマット操作 (%形式) | Python Snippets