Ad
Strings
Data Types

Use the way we handle this problem with our brain.
We count and put a comma every three digits.

Code
Diff
  • def f(n):
        l = [digit for digit in str(n)]
        
        count_to_three = 1
        for i in range(len(l) - 1, 0, -1):
            if count_to_three != 3:
                count_to_three += 1
            else:
                l.insert(i, ',')
                count_to_three = 1
                
        return ''.join(l)
    • def f(n):
    • G = 3
    • s = str(n)
    • r = len(s) % G
    • def make(s):
    • if r:
    • yield s[:r]
    • for i in range(r, len(s), G):
    • yield s[i:i+G]
    • return ','.join(make(s))
    • l = [digit for digit in str(n)]
    • count_to_three = 1
    • for i in range(len(l) - 1, 0, -1):
    • if count_to_three != 3:
    • count_to_three += 1
    • else:
    • l.insert(i, ',')
    • count_to_three = 1
    • return ''.join(l)