Pythonでゼロ埋めする方法(zfill/rjust/ljust/center)

投稿者: | 2020年10月6日

Pythonでゼロ埋めする方法(zfill/rjust/ljust/center)です

zfill 左埋め

test = '12345'
print('zfill1 ' + test.zfill(10))

test = '+12345'
print('zfill2 ' + test.zfill(10))

test = '-12345'
print('zfill3 ' + test.zfill(10))

zfillの実行結果

zfill1 0000012345
zfill2 +000012345
zfill3 -000012345

文字列に+-記号が入っている場合は+- と文字列の間を埋めるみたい

rjust 右寄せ(左埋め)

test = '12345'
print('rjust ' + test.rjust(10, '0'))

rjustの実行結果

rjust 0000012345

ljust 左寄せ(右埋め)

test = '12345'
print('ljust ' + test.ljust(10, '0'))

ljustの実行結果

ljust 1234500000

center 中央寄せ(左右埋め)

test = '12345'
print('center ' + test.center(10, '0'))

centerの実行結果

center 0012345000

文字列に+-記号が入っている場合も同じ結果になるみたい