e.g.
123123123 -> 123,123,123
12312312 -> 12,312,321
1000 -> 1,000
This is my solve for the 16th June Data I/O bookclub challenge.
| def format_num(x: int) -> str: | |
| s = str(x)[::-1] | |
| return ''.join( | |
| c+(',' if (i+1)%3 == 0 else '') for i, c in enumerate(s) | |
| )[::-1].lstrip(',') |
| def format_num(x: int) -> str: | |
| return ''.join( | |
| c+(',' if (i+1)%3 == 0 else '') for i, c in enumerate(str(x)[::-1]) | |
| )[::-1].lstrip(',') |
| def format_num(x: int) -> str: | |
| return ''.join( | |
| c+','*(not (i+1)%3) for i, c in enumerate(str(x)[::-1]) | |
| )[::-1].lstrip(',') |
| format_num = lambda x: ''.join(c+','*(not (i+1)%3) for i, c in enumerate(str(x)[::-1]))[::-1].lstrip(',') |
| def format_num(x: int) -> str: | |
| s = str(x) # int to string | |
| s = s[::-1] # reverse string | |
| out_str = "" # Accumulator for our output string | |
| for i, c in enumerate(s): # Iterate reversed string by char (c) and char index (i) | |
| append_str = c # Local var for next string(s) to append to the accumulator | |
| if not (i+1)%3: # Congruent to `if (i+1)%3 == 0` - modulo index to determine when 3n chars have been traversed | |
| append_str += ',' # char then comma (since string construction is backwards) on every 3rd char | |
| out_str += append_str | |
| out_str = out_str[::-1] # Reverse the constructed string, so it's now in the correct order | |
| out_str = out_str.lstrip(',') # If the digital length of input x is any 3n, unnecessary leading comma will be present - strip it | |
| return out_str # :3 |