Verbally format a number in Python

前端 未结 3 731
春和景丽
春和景丽 2021-01-05 04:33

How do pythonistas print a number as words, like the equivalent of the Common Lisp code:

[3]> (format t \"~r\" 1e25)
nine septillion, nine hundred and nin         


        
3条回答
  •  遥遥无期
    2021-01-05 05:15

    Here as a way to do it:

    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]
    

    It does this:

    >>> abbreviate(11423)
    11.43 K
    

提交回复
热议问题