问题
I don't really know the "name" for this problem, so it might be a incorrect title, but the problem is simple, if I have a number
for example:
number = 23543
second = 68471243
I want to it make print()
like this.
23,543
68,471,243
I hope this explains enough or else add comments. Any help is appreciated!
回答1:
If you only need to add comma as thousand separator and are using Python version 3.6 or greater:
print(f"{number:,g}")
This uses the formatted string literals style. The item in braces {0}
is the object to be formatted as a string. The colon :
states that output should be modified. The comma ,
states that a comma should be used as thousands separator and g
is for general number. [1]
With older Python 3 versions, without the f-strings:
print("{0:,g}".format(number))
This uses the format-method of the str-objects [2]. The item in braces {0}
is a place holder in string, the colon :
says that stuff should be modified. The comma ,
states that a comma should be used as thousands separator and g
is for general number [3]. The format
-method of the string object is then called and the variable number
is passed as an argument.
The 68,471,24,3 seems a bit odd to me. Is it just a typo?
Formatted string literals
Python 3 str.format()
Python 3 Format String Syntax
回答2:
The easiest way is setting the locale to en_US.
Example:
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
number = 23543
second = 68471243
print locale.format("%d", number, grouping=True)
print locale.format("%d", second, grouping=True)
prints:
23,543
68,471,243
来源:https://stackoverflow.com/questions/18913790/adding-thousand-separator-while-printing-a-number