Andrea Bergonzo
Andrea Bergonzo

Reputation: 5180

Python formatted literal string and thousand separator

Is there a way to combine python3.6 formatted literal strings (PEP498) with format specifications?

print('Count: {:,}'.format(count)) # Count: 10,000

print(f'Count: {count}') # Count: 10000

The closest thing I can think of is using the format function like this:
print(f'Count: {format(count, "6,d")}') # Count: 10,000 # can use "6,d" or any other format that puts thousands separators

Is this the best way to do that?

Upvotes: 0

Views: 561

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19422

from the link you gave:

F-strings use the same format specifier mini-language as str.format. Similar to str.format(), optional format specifiers maybe be included inside the f-string, separated from the expression (or the type conversion, if specified) by a colon. If a format specifier is not provided, an empty string is used.

as for your example:

>>> count = 10000
>>> print('Count: {:,}'.format(count))
Count: 10,000
>>> print(f'Count: {count:,}')
Count: 10,000

Upvotes: 1

Related Questions