Skip to content

Instantly share code, notes, and snippets.

@MolarFox
Last active June 16, 2022 04:18
Show Gist options
  • Select an option

  • Save MolarFox/cc177d8feb6549e10ec0d6e7e1335d73 to your computer and use it in GitHub Desktop.

Select an option

Save MolarFox/cc177d8feb6549e10ec0d6e7e1335d73 to your computer and use it in GitHub Desktop.
Data I/O Bookclub - 16 June 2022

A function that takes in an integer string, and converts it to "pretty" format aka comma-separated

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment