如何定义新的字符串格式化程序(How to define a new string formatter)

编程入门 行业动态 更新时间:2024-10-20 00:43:19
如何定义新的字符串格式化程序(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^3

You 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

更多推荐

本文发布于:2023-08-02 08:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   定义   程序   formatter   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!