Separate numbers by 3 digits (python)

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

Separate numbers by 3 digits (python)
Primality test by Python
Visualization memo by Python
Memorize Python commentary 3 --Numbers
Beamformer response by python
Prime numbers in Python
Speech recognition by Python MFCC
[Python] Obtaining American-style week numbers
EXE Web API by Python
Parameter setting by python configparser
Pin python managed by conda
Determine prime numbers with python
Keyword extraction by MeCab (python)
Markov switching model by Python
Image processing by python (Pillow)
Python started by C programmers
Platform (OS) determination by Python
Sort by date in python
Handle complex numbers in Python
Playing handwritten numbers with python Part 1
[Python] Sort iterable by multiple conditions
Expansion by argument of python dictionary
Machine learning summary by Python beginners
Learn Python by drawing (turtle graphics)
Python development helped by Jenkins-Unit test
python sql statement extracted by time
Make Python dict accessible by Attribute
OS determination by Makefile using Python
Typing automation notes by Python beginners
[Python] Convert natural numbers to ordinal numbers
Interval scheduling learning memo ~ by python ~
Separate display of Python graphs (memo)
Behavior of python3 by Sakura's server
Convert decimal numbers to n-ary numbers [python]
Law of large numbers in python
[Python] nCr mod Compute prime numbers
100 Language Processing Knock Chapter 1 by Python
Story of power approximation by Python
Sorting files by Python naming convention
[Python] Change the alphabet to numbers