LoginSignup
2
2

More than 3 years have passed since last update.

数字を3桁ごとに区切る(python)

Last updated at Posted at 2020-11-19

'{:,}'.format()を使って98765の数字を98,765にする。
数値(int)じゃないと区切れない。文字列(str)だとValueErrorになる。

# python

>>> l=['12345',98765]  # 12345は文字列、98765は数値なリストを作る
>>> 
>>> l
['12345', 98765]
>>> 
>>> print(type(l[0]))  # 型の確認
<type 'str'>
>>> print(type(l[1]))  # 型の確認
<type 'int'>
>>> 
>>> l[0] = '{:,}'.format(l[0])  # str型を区切ろうとしてもエラーになる
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Cannot specify ',' with 's'.
>>> 
>>> l[1] = '{:,}'.format(l[1])  # int型だと問題ない
>>> 
>>> l
['12345', '98,765']
>>>
>>> type(l[1])  # ただし、区切ったあとはintじゃなくてstrになる。
<type 'str'>
>>>
>>> l[0] = '{:,}'.format(int(l[0]))  #str型のところはint()を使う
>>> l
['12,345', '98,765']
>>>

f-stringを使ってみた

>>> m
['12345', 98765]
>>>
>>>
>>> print(f'{m[0]:,}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Cannot specify ',' with 's'.
>>>
>>>
>>> print(f'{int(m[0]):,}')
12,345
>>>
>>>
>>> print(f'{m[1]:,}')
98,765
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2