用Python语言格式化一个数字

2024-06-02 04:32:22 发布

您现在位置:Python中文网/ 问答频道 /正文

像pythonisp一样的普通单词怎么做:

[3]> (format t "~r" 1e25)
nine septillion, nine hundred and ninety-nine sextillion, nine hundred and ninety-nine quintillion, seven hundred and seventy-eight quadrillion, one hundred and ninety-six trillion, three hundred and eight billion, three hundred and sixty-one million, two hundred and sixteen thousand

Tags: andformat单词onethreehundredsevennine
3条回答

以下是一种方法:

def abbreviate(x):
    abbreviations = ["", "K", "M", "B", "T", "Qd", "Qn", "Sx", "Sp", "O", "N", 
    "De", "Ud", "DD"]
    thing = "1"
    a = 0
    while len(thing) < len(str(x)) - 3:
        thing += "000"
        a += 1
    b = int(thing)
    thing = round(x / b, 2)
    return str(thing) + " " + abbreviations[a]

它的作用是:

^{pr2}$

我刚开始用土耳其语工作,可能会有帮助。在

https://github.com/guneysus/humanizer-tr

它返回一个字符串列表,并附带简单的测试函数randomizer()prettizer()和核心函数{}

它可以处理非常大的数字,因为它没有使用除法,而是使用字符串分割和操作。在

您可以输入偶数或字符串。在

因为我没有写数字验证,它甚至可以处理非数字文本 :)

>>> humanizer('STACK OVER FLOW')
['STA Trilyon', 'CK  Milyar', 'OVE Milyon', 'R F Bin', 'LOW']

python内核中没有,但有第三方库num2words

>>> from num2words import num2words
>>> num2words(1e25)
'ten septillion, one billion, seventy-three million, seven hundred and forty-one thousand, eight hundred and twenty-four'

>>> num2words(10000000000000000000000000)
'ten septillion'

(请注意,1e25并没有精确地转换为整数,在您的示例中也是如此)

相关问题 更多 >