前提条件
本記事では 文字列型(str) を対象としています。数値型(int、float) の場合は 文字列型 に型変換するか、次の記事を参照してください。 数値型 を 文字列型 に型変換# int型
int_value = 12345
# str型に型変換
str_value = str(int_value)
ゼロパディング(符号あり)
次のサンプルコードは 文字列 '+123' と '-123' を 5桁でゼロ埋めしています。 おすすめは zfill関数 で、符号を考慮してゼロ埋めが行われます。str_p = '+123'
str_m = '-123'
# zfillメソッド
print(str_p.zfill(5)) # -> '+0123'
print(str_m.zfill(5)) # -> '-0123'
# rjustメソッド
print(str_p.rjust(5, '0')) # -> '0+123'
print(str_m.rjust(5, '0')) # -> '0-123'
# formatメソッド
print('{:0>5}'.format(str_p)) # -> '0+123'
print('{:0>5}'.format(str_m)) # -> '0-123'
# f-string
print(f'{str_p:0>5}') # -> '0+123'
print(f'{str_m:0>5}') # -> '0-123'
-
f-string(フォーマット済み文字列リテラル)を使用するには、Python3.6以上のバージョンが必要です。
バージョンを確認するには次の記事を参照してください。
ゼロパディング(符号無し)
符号が無い場合、結果は同じです。str_value = '123'
# zfillメソッド
print(str_value.zfill(5)) # -> '00123'
# rjustメソッド
print(str_value.rjust(5, '0')) # -> '00123'
# formatメソッド
print('{:0>5}'.format(str_value)) # -> '00123'
# f-string
print(f'{str_value:0>5}') # -> '00123'
数値型を渡すと?
zfillメソッド と rjustメソッド は テキストシーケンス型(str型) のメソッドです。 整数型(int型)のオブジェクトにはzfillとrjustメソッドは存在しないため、エラーが発生します。num = 123
# zfillメソッド
print(num.zfill(5))
# -> AttributeError: 'int' object has no attribute 'zfill'
# rjustメソッド
print(num.rjust(5, '0'))
# -> AttributeError: 'int' object has no attribute 'rjust'
# formatメソッド
print('{:0>5}'.format(num)) # -> '00123'
# f-string
print(f'{num:0>5}') # -> '00123'
None を渡すと?
いづれもエラーが発生します。変数に None が代入される可能性がある場合、空文字列に変換するなどの対策が必要です。str_value = None
# zfillメソッド
print(str_value.zfill(5))
# -> AttributeError: 'NoneType' object has no attribute 'zfill'
# rjustメソッド
print(str_value.rjust(5, '0'))
# -> AttributeError: 'NoneType' object has no attribute 'rjust'
# formatメソッド
print('{:0>5}'.format(str_value))
# -> TypeError: unsupported format string passed to NoneType.__format__
# f-string
print(f'{str_value:0>5}')
# -> TypeError: unsupported format string passed to NoneType.__format__
None を考慮する場合
str_value = None
# None のとき、空文字列に変換
if str_value is None:
str_value = ''
print(str_value.zfill(5)) # -> '00000'
参考資料
- Python公式ドキュメント - str.zfill
- Python公式ドキュメント - str.rjust
- Python公式ドキュメント - str.format
- Python公式ドキュメント - 書式指定文字列の文法
- Python公式ドキュメント - フォーマット済み文字列リテラル
検証環境
- Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32
- Microsoft Windows 10 Enterprise Version 22H2 OS Build 19045.3570 Experience: Windows Feature Experience Pack 1000.19052.1000.0