简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM