Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number 1234567 as 1,234,567. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.

It does not need to be locale-specific to decide between periods and commas. I would prefer something as simple as reasonably possible.

1 Answer

0 votes
by (106k points)

This can be easily done by using  f-strings:

num = 10000000

print(f"{num:,d}")

image

  • In this method, the part after the colon is the format specifier. The comma is the separator character you want, 

  • This is equivalent of using format(num, ",d") for older versions of python.

  • we can use my_string = '{:,.2f}'.format(my_number) to convert float value into commas as thousands separators.

my_number = 4385893.382939491

my_string = '{:,.2f}'.format(my_number)

image

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...