Use '{:,}'. format ()
to change the number 98765 to 98,765.
It cannot be separated unless it is a numerical value (int). If it is a character string (str), a ValueError will occur.
# python
>>> l=['12345',98765] #12345 is a string, 98765 is a numeric list
>>>
>>> l
['12345', 98765]
>>>
>>> print(type(l[0])) #Type confirmation
<type 'str'>
>>> print(type(l[1])) #Type confirmation
<type 'int'>
>>>
>>> l[0] = '{:,}'.format(l[0]) #An error occurs when trying to separate str types
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Cannot specify ',' with 's'.
>>>
>>> l[1] = '{:,}'.format(l[1]) #There is no problem if it is an int type
>>>
>>> l
['12345', '98,765']
>>>
>>> type(l[1]) #However, after separating, it becomes str instead of int.
<type 'str'>
>>>
>>> l[0] = '{:,}'.format(int(l[0])) #str type is int()use
>>> l
['12,345', '98,765']
>>>
I tried using 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
Recommended Posts