Program to find number with thousand separator in Python

When working with large numbers, it's often helpful to format them with thousand separators for better readability. Python provides several ways to add commas as thousand separators to numbers.

So, if the input is like n = 512462687, then the output will be "512,462,687"

Method 1: Using Built-in format() Function

The simplest approach is to use Python's built-in format() function with the comma separator ?

def format_number(n):
    return format(n, ',')

n = 512462687
result = format_number(n)
print(result)
print(type(result))
512,462,687
<class 'str'>

Method 2: Using f-string Formatting

F-strings provide a modern and readable way to format numbers ?

def format_with_fstring(n):
    return f"{n:,}"

n = 512462687
result = format_with_fstring(n)
print(result)

# Multiple examples
numbers = [1000, 50000, 1234567, 987654321]
for num in numbers:
    print(f"{num:,}")
512,462,687
1,000
50,000
1,234,567
987,654,321

Method 3: Manual Implementation

For educational purposes, here's how to implement thousand separators manually ?

def manual_separator(n):
    num_str = str(n)
    reversed_str = num_str[::-1]
    
    result = ""
    for i in range(len(reversed_str)):
        if i % 3 == 0 and i != 0:
            result += ','
        result += reversed_str[i]
    
    return result[::-1]

n = 512462687
result = manual_separator(n)
print(result)
512,462,687

Method 4: Using locale Module

The locale module can format numbers according to regional conventions ?

import locale

# Set locale to US for comma separators
try:
    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
except:
    locale.setlocale(locale.LC_ALL, 'C')  # Fallback

def format_with_locale(n):
    return locale.format_string("%d", n, grouping=True)

n = 512462687
result = format_with_locale(n)
print(result)
512,462,687

Comparison

Method Syntax Best For
format() format(n, ',') Simple, built-in solution
f-string f"{n:,}" Modern Python (3.6+)
Manual Custom function Educational/custom logic
locale locale.format_string() International formatting

Handling Negative Numbers

All methods work correctly with negative numbers ?

negative_num = -512462687
print(f"f-string: {negative_num:,}")
print(f"format(): {format(negative_num, ',')}")
f-string: -512,462,687
format(): -512,462,687

Conclusion

Use f"{n:,}" for modern Python applications as it's clean and readable. The format(n, ',') function works in all Python versions and is equally effective for adding thousand separators.

Updated on: 2026-03-25T20:19:54+05:30

573 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements