Pythonでフォーマットして文字列出力
目次
フォーマットして文字列出力
PHP sprintf
<?php $str = sprintf('今日は%s、明日は%s', '晴れ', '曇り'); echo $str; // 今日は晴れ、明日は曇り $str = sprintf('今日は%1$s、明日も%1$s', '晴れ'); echo $str; // 今日は晴れ、明日も晴れ $str = sprintf('%.2f', 1 / 3); echo $str; // 0.33 $str = sprintf('%04d', 12); echo $str; // 0012 $str = sprintf('%1$04d, %1$08d', 12); echo $str; // 0012, 00000012
直接出力する場合は printf
を使用できます。
Python %演算子
2.x 3.x
# -*- coding: utf-8 -*- str = u'今日は%s、明日は%s' % (u'晴れ', u'曇り') print(str) # 今日は晴れ、明日は曇り str = u'今日は%(weather)s、明日も%(weather)s' % {'weather': u'晴れ'} print(str) # 今日は晴れ、明日も晴れ str = '%.2f' % (1.0 / 3.0) print(str) # 0.33 str = '%04d' % 12 print(str) # 0012 str = '%(i)04d, %(i)08d' % {'i': 12} print(str) # 0012, 00000012