I was working on a little Python challenge that was a bit more difficult than expected: format any non-negative number so 1000
turns into "1,000"
, 10000000
into "10,000,000"
and so forth. I managed to do it, but I find my solution not very readable:
def formatting(n):
m = str(n) # Turn it into string
m2 = [] # Empty list that will have the split version of the final number
for i in range(0,len(m),3): # Iterate every three elements
m2.append(m[::-1][i:i+3][::-1]) # Append last three numbers, second to last three numbers, etc.
m2.append(',') # Add a comma between loops
m3 = ''.join(m2[::-1])[1:] # Join and drop the first element which is always a comma.
return m3
This works but it isn't as nice as it could be. What can be done?
m = str(m)
bem = str(n)
? \$\endgroup\$ – Linny Sep 24 '19 at 19:39