Python - 数値を 3桁のカンマ区切りに整形 + 右寄せする

3桁のカンマ区切りに整形するにはフォーマットで「:,」を指定し、カンマ区切り + 右寄せにするには「:>桁数,」を指定します。

カンマ区切りにする方法

フォーマット済み文字列リテラル(f-string) の場合
結果文字列 = f'{変数:,}'

str.format() の場合

結果文字列 = '{num:,}'.format(num=変数)

サンプルコード

intValue1 = 123
intValue2 = 123456789

# フォーマット済み文字列リテラル(f-string) の場合
print('-- f-string を使用 --')
print(f'{intValue1:,}')
print(f'{intValue2:,}')
# 結果
# 123
# 123,456,789

#  str.format() の場合
print('')
print('----- str.format()を使用 -----')
print('{n:,}'.format(n=intValue1))
print('{n:,}'.format(n=intValue2))
# 結果
# 123
# 123,456,789
実行結果

カンマ区切り + 右揃え

右揃えにするには フォーマットに「:>桁数,」を指定します。

フォーマット済み文字列リテラル(f-string) の場合

結果文字列 = f'{変数:>桁数,}'
str.format() の場合
結果文字列 = '{num:>桁数,}'.format(num=変数)

サンプルコード

intValue1 = 123
intValue2 = 123456789

# フォーマット済み文字列リテラル(f-string) の場合
print('')
print('----- 右揃え(f-string) -----')
print(f'{intValue1:>20,}')
print(f'{intValue2:>20,}')
# 結果
#                 123
#         123,456,789

#  str.format() の場合
print('')
print('----- 右揃え(str.format) -----')
print('{n:>20,}'.format(n=intValue1))
print('{n:>20,}'.format(n=intValue2))
# 結果
#                 123
#         123,456,789

実行結果

検証環境

関連ページ