打印数字时添加千位分隔符 [英] Adding thousand separator while printing a number
问题描述
我真的不知道这个问题的名称",所以它可能是一个不正确的标题,但问题很简单,如果我有一个数字
例如:
编号 = 23543第二个 = 68471243
我想让 print()
像这样.
23,543
68,471,243
我希望这足够解释或者添加评论.任何帮助表示赞赏!
如果您只需要添加逗号作为千位分隔符并且使用 Python 3.6 或更高版本:
print(f"{number:,g}")
这使用格式化的字符串文字样式.大括号 {0}
中的项目是要格式化为字符串的对象.冒号 :
表示应该修改输出.逗号 ,
表示逗号应用作千位分隔符,而 g
表示一般数字.[1]
使用较旧的 Python 3 版本,没有 f 字符串:
print("{0:,g}".format(number))
这使用 str-objects 的格式方法 [2].大括号 {0}
中的项目是字符串中的占位符,冒号 :
表示应该修改内容.逗号 ,
表示逗号应用作千位分隔符,g
用于一般数字 [3].然后调用字符串对象的 format
方法,并将变量 number
作为参数传递.
68,471,24,3 对我来说似乎有点奇怪.只是打字错误吗?
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!
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?
这篇关于打印数字时添加千位分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!