如何定义新的字符串格式化程序(How to define a new string formatter)
我经常使用这个小函数eng(x)特别是以易于阅读的方式显示大小数字。
这允许我写"%e" % (number) 。
我希望能够写出"%n" % (number)并获得由此eng(x)函数格式化的数字。
有没有办法做到这一点?
I often use this small function eng(x) especially to show big or small numbers in an easy to read way.
This allows me to write"%e" % (number).
I would like to be able to write "%n" % (number) and get the number formatted by this eng(x) function.
Is there a way to do this?
最满意答案
您可以实现一个新的数字类:
from math import floor, log10 class snumber(float): def powerise10(x): if x == 0: return 0 , 0 Neg = x <0 if Neg : x = -x a = 1.0 * x / 10**(floor(log10(x))) b = int(floor(log10(x))) if Neg : a = -a return a ,b def __str__(x): a , b = snumber.powerise10(x) if -3<b<3: return "%.4g" % x a = a * 10**(b%3) b = b - b%3 return "%.4g*10^%s" %(a,b) print "{}".format(snumber(100000))得到:
100*10^3You can implement a new number class:
from math import floor, log10 class snumber(float): def powerise10(x): if x == 0: return 0 , 0 Neg = x <0 if Neg : x = -x a = 1.0 * x / 10**(floor(log10(x))) b = int(floor(log10(x))) if Neg : a = -a return a ,b def __str__(x): a , b = snumber.powerise10(x) if -3<b<3: return "%.4g" % x a = a * 10**(b%3) b = b - b%3 return "%.4g*10^%s" %(a,b) print "{}".format(snumber(100000))Gives:
100*10^3更多推荐
发布评论