Add Thousand Separators to a Number String

Easy ⏱ 8 min 75% acceptance ★★★★☆ 4.3
Write add_thousand_separators(n) that converts an integer n into a string with commas every three digits from the right (e.g. 1234567 becomes "1,234,567"), preserving a leading minus sign for negative numbers.

Examples

Example 1
Input
n = 1234567
Output
'1,234,567'
Explanation

Digits are grouped into threes from the right.

Example 2
Input
n = -4200
Output
'-4,200'
Explanation

The minus sign is kept in front, outside the grouping logic.

Example 3
Input
n = 42
Output
'42'
Explanation

Numbers under 1000 need no comma.

Constraints

  • n is an integer (can be negative or zero).

Topics

StringsString Building

Companies

WalmartFlipkart

Hints

Hint 1

Work with `str(abs(n))` and peel off the last 3 characters repeatedly.

Hint 2

Re-attach the minus sign at the end if n was negative.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.