如何用逗号打印数字作为千位分隔符?

How to print number with commas as thousands separators?(如何用逗号打印数字作为千位分隔符?)

本文介绍了如何用逗号打印数字作为千位分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Python 2.6.1 中打印一个整数,用逗号作为千位分隔符.例如,我想将数字 1234567 显示为 1,234,567.我该怎么做呢?我在谷歌上看过很多例子,但我正在寻找最简单实用的方法.

I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number 1234567 as 1,234,567. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.

在句点和逗号之间进行选择不需要特定于语言环境.我更喜欢尽可能简单的东西.

It does not need to be locale-specific to decide between periods and commas. I would prefer something as simple as reasonably possible.

推荐答案

Locale unaware

'{:,}'.format(value)  # For Python ≥2.7
f'{value:,}'  # For Python ≥3.6

区域感知

import locale
locale.setlocale(locale.LC_ALL, '')  # Use '' for auto, or force e.g. to 'en_US.UTF-8'

'{:n}'.format(value)  # For Python ≥2.7
f'{value:n}'  # For Python ≥3.6

参考

根据 格式规范迷你语言,

',' 选项表示使用逗号作为千位分隔符.对于区分区域设置的分隔符,请改用 'n' 整数表示类型.

The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.

这篇关于如何用逗号打印数字作为千位分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何用逗号打印数字作为千位分隔符?

基础教程推荐