Sometimes, while working with currencies, we need to put commas between numbers to represent a currency, hence given a string, we can have a problem to insert commas into them. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using str.format() The string format function can be used by supplying the valid formatter to perform the formatting. The string formatter is called with the value as argument to perform this particular task.
Python3
test_num = 1234567
print ( "The original number is : " + str (test_num))
res = ( '{:,}' . format (test_num))
print ( "The number after inserting commas : " + str (res))
|
Output
The original number is : 1234567
The number after inserting commas : 1,234,567
Time complexity: O(1) as the formatting operation is a constant time operation.
Auxiliary space: O(1) as no additional data structure is used and the result is stored in a variable.
Method #2 : Using format() This task can also be performed without taking the help of format library of strings but the normal format library that can use the “d” notation of numbers and simply insert the commas where required.
Python3
test_num = 1234567
print ( "The original number is : " + str (test_num))
res = ( format (test_num, ',d' ))
print ( "The number after inserting commas : " + str (res))
|
Output
The original number is : 1234567
The number after inserting commas : 1,234,567
Time complexity: O(1) The time complexity of the program is constant time because it does not depend on the size of the input.
Auxiliary space: O(1) The program uses a constant amount of auxiliary space.
Method #3: Using re.sub()
The re.sub() method can be used along with regular expressions to match the required pattern of digits and insert commas in between them.
Python3
import re
test_num = 1234567
print ( "The original number is : " + str (test_num))
res = re.sub(r '(\d{3})(?=\d)' , r '\1,' , str (test_num)[:: - 1 ])[:: - 1 ]
print ( "The number after inserting commas : " + str (res))
|
Output
The original number is : 1234567
The number after inserting commas : 1,234,567
This method will match every 3 digits in the number, and insert a comma before it using a positive lookahead. The string is first reversed using slicing so that the commas are inserted from right to left, and then reversed back to get the final output.
Time Complexity and Auxiliary space of this approach is O(n)
Method#4: Using f-string
Python3
test_num = 1234567
print ( "The original number is : " + str (test_num))
res = f "{test_num:,}"
print ( "The number after inserting commas : " + str (res))
|
Output
The original number is : 1234567
The number after inserting commas : 1,234,567
Time Complexity: O(n)
Auxiliary space : O(1)
Method#5: Using insert_commas():
Python3
def insert_commas(num):
num_str = str (num)
result = ""
for i, digit in enumerate (num_str[:: - 1 ]):
if i > 0 and i % 3 = = 0 :
result = "," + result
result = digit + result
return result
test_num = 1234567
print ( "The original number is:" , test_num)
res = insert_commas(test_num)
print ( "The number after inserting commas:" , res)
|
Output
The original number is: 1234567
The number after inserting commas: 1,234,567
Time Complexity : O(n)
Auxiliary space : O(n)
Method 6 : use recursion.
step-by-step approach:
- Define a recursive function insert_commas_recursive() that takes two arguments: the number to be formatted as a string, and a counter that keeps track of the number of digits processed so far.
- If the length of the input string is less than or equal to 3, return the input string as-is.
- Otherwise, call insert_commas_recursive() recursively with the input string minus the last three digits, and increment the counter by 3.
- Concatenate the result of the recursive call with a comma and the last three digits of the input string.
- Return the final formatted string.
- In the main code block, convert the input number to a string, and call the insert_commas_recursive() function with the string and a counter of 0.
- Print the original number and the formatted number.
Python3
def insert_commas_recursive(num_str, counter):
if len (num_str) < = 3 :
return num_str
else :
result = insert_commas_recursive(num_str[: - 3 ], counter + 3 )
return result + ',' + num_str[ - 3 :]
test_num = 1234567
num_str = str (test_num)
res = insert_commas_recursive(num_str, 0 )
print ( "The original number is:" , test_num)
print ( "The number after inserting commas:" , res)
|
Output
The original number is: 1234567
The number after inserting commas: 1,234,567
The time complexity : O(n) where n is the number of digits in the number.
auxiliary space: O(n).
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
30 Apr, 2023
Like Article
Save Article