Often, you will want to format your numbers in Python because it’s quite hard for a user to read 10000000000 and immediately understand it as: 10,000,000,000. So, this little article will show you one possible way to do the formatting – using many of the Python concepts discussed in previous articles and in my Udemy course.
In the below, I have defined a function called format number. It takes in a single argument which is the original number from the user. It converts that number to a string & then converts it to a list.
We then calculate how many commas we need in our number by taking the length of the number and dividing it by 3 (becuase we put a comma every 3 numbers).
We then break out into a while loop & say ‘while there is still a comma to insert, keep going’. Inside the loop, we jump back 3 spaces and put a comma in that index of the list. We only do that if the index is not longer than the list, so we avoid having a comma right at the beginning of the number.
We then convert back to a string and we are done!
def format_number(number):
x = list(str(number))
length = len(x)
commas = int(length/3)
print(commas)
index = 0
attempt = 1
while commas >0:
if attempt == 1:
index = index-3
else:
index = index-4
commas = commas -1
if abs(index) != len(x):
x.insert(index, ',')
attempt = attempt + 1
x = ''.join(x)
print(x)
format_number(1000000000000)