
Simple Projects using Python
Python program to add thousands separator
Project Instructions
Write a Python function named “thousands” that takes a number as its only parameter. Your function should return the number with commas as a thousands separator. It is one of Practity’s simple projects using Python to improve your problem solving skills and level up your knowledge of functions and loops.
For example:
thousands(159652487)
159,652,487
Steps
- Define a function named “thousands” that takes a non-negative number as its parameter.
- Convert the number to a string using the “str()” function.
- Initialize an empty string to store the result.
- Iterate over the characters in the string representation of the number.
- For every character, check if its position in the string, counting from the right, is a multiple of 3 (indicating a thousands place).
- If the position is a multiple of 3 and not the first character, append a comma (“,”) to the result string.
- Append the current character to the result string.
Project Solved
## We define the function
def thousands(number):
number_str = str(number)
result = ""
for i, char in enumerate(number_str[::-1]):
if i % 3 == 0 and i != 0:
result += ","
result += char
return result[::-1]