在Python中将长数字格式化为字符串

在Python中将长数字格式化为字符串

本文介绍了在Python中将长数字格式化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,将整数转换为代表数千个字符串的字符串的简单方法是什么?使用K代表数以百万计的字符串,并且在逗号之后留下几个数字?

d喜欢显示7436313为7.44M,2345为23.4K。

是否有一些%字符串格式化运算符可用于此?或者这样做只能在循环中实际上除以1000,并逐步构建结果字符串?

解决方案

不要以为有一个内置函数可以做到这一点。你必须推出你自己的,例如:

$ p $ def human_format(num):
magnitude = 0
,而abs(num)> = 1000:
幅度+ = 1
num / = 1000.0
#如果你需要的话可以添加更多的后缀
return'%.2f% s'%(num,['','K','M','G','T','P'] [magnitude])

print('答案是%s '%human_format(7436313))#打印'答案是7.44M'


What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma?

I'd like to show 7436313 as 7.44M, and 2345 as 2,34K.

Is there some % string formatting operator available for that? Or that could be done only by actually dividing by 1000 in a loop and constructing result string step by step?

解决方案

I don't think there's a built-in function that does that. You'll have to roll your own, e.g.:

def human_format(num):
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    # add more suffixes if you need them
    return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])

print('the answer is %s' % human_format(7436313))  # prints 'the answer is 7.44M'

这篇关于在Python中将长数字格式化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:26