文字列のフォーマット(3)
きのうはむずかしいことを考えすぎたので、単純にいっぱい練習してみたいと思います。
# 普通に >>> "%d" % 10 '10' # これもCと一緒 >>> "%04d" % 10 '0010' # 二つ以上はタプルで指定 >>> "%d %d" % (10, 20) '10 20' # 桁数もタプルで指定してみる >>> "%0*d" % (4, 10) '0010' # 16進数 >>> "%04x" % 255 '00ff' # ``別形式'' >>> "%#x" % 255 '0xff' # マップを使って。間違ったのも書いておこう。 >>> "%(one)d %04(two)d" % {'one':1, 'two':2} Traceback (most recent call last): File "<pyshell#104>", line 1, in -toplevel- "%(one)d %04(two)d" % {'one':1, 'two':2} TypeError: not enough arguments for format string # 正解はこちら >>> "%(one)d %(two)04d" % {'one':1, 'two':2} '1 0002'
``別形式''って何なのか悩んだ。英文で alternate form って書いてありました。