Thousands separators

When doing string formatting with big integers, you may want to include thousands separators to make numbers easier to read. You can add commas, underscores, or a locale-appropriate separator, using the specifiers ,, _, or n, respectively:

bignum = 123541241234

print(f"Big money ${bignum:,}")
## Big money $123,541,241,234

print(f"Big money ${bignum:_}")
## Big money $123_541_241_234

print(f"Big money ${bignum:n}")
## Big money $123541241234

When you specify that you are printing binary (b), octal (o), or hexadecimal digits (x/X), _ can be used to insert underscores every four digits:

bits = 0b10_0000_1111_0110

print(f"{bits:b}")   # 10000011110110
print(f"{bits:_b}")  # 10_0000_1111_0110
hex_value = 0xfa35_de98

print(f"{hex_value:x}")   # fa35de98
print(f"{hex_value:_x}")  # fa35_de98

Improve your Python 🐍 fluency and algorithm knowledge 🎯

Get ready for 12 intense days of problem-solving. The β€œAlgorithm Mastery Bootcamp” starts December 1st and it will feature 24 programming challenges, live analysis sessions, a supportive community of like-minded problem-solvers, and more! Join now and become the Python expert others can rely on.

References

Previous Post Next Post

Blog Comments powered by Disqus.