Python | Add comma between numbers

Python Methods and Functions

Method # 1: Using str.format()
The string formatting function can be used by specifying the correct formatter to perform formatting. The string formatter is called with a value as an argument to accomplish this specific task.

# Python3 code to demonstrate how it works
# Adding a comma between numbers
# Using str.format ()

 
# initialization number

test_num = 1234567

  
# print original number

print ( " The original number is: " + str (test_num) )

  
# Using str.format ()
# Adding a comma between numbers

res = ( '{:,}' . format (test_num))

 
# print result

print ( "The number after inserting commas:" + str (res))

Output:

 The original number is: 1234567 The number after inserting commas: 1, 234 , 567 

Method # 2: Using format()
This task can also be performed by without resorting to a string format library, but a regular format library that can use the "d" notation for numbers and just insert commas where necessary.

# Python3 code to demonstrate how it works
# Adding a comma between numbers
# Using the () format

 
# initialization number

test_num = 1234567

 
# printing original number

print ( "The original number is:" + str (test_num))

 
# Using the () format
# Adding a comma between numbers

res = ( format (test_num, ', d' ))

  
# print result

print ( "The number after inserting commas:" + str (res))

Exit:

 The original number is: 1234567 The number after inserting commas: 1, 234, 567 




Get Solution for free from DataCamp guru