首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >输入浮点值而不导致零

输入浮点值而不导致零
EN

Stack Overflow用户
提问于 2019-06-21 04:28:59
回答 2查看 0关注 0票数 0

尝试使用格式说明符来打印一个小于1而没有前导零的浮点数。我想出了一些黑客,但我认为有一种方法可以在格式说明符中删除前导零。我在文档中找不到它。

问题

>>> k = .1337
>>> print "%.4f" % k
'0.1337'

>>> print ("%.4f" % k) [1:]
'.1337'
EN

Stack Overflow用户

发布于 2019-06-21 12:52:33

您可以使用以下MyFloat类而不是内置float类。

def _remove_leading_zero(value, string):
    if 1 > value > -1:
        string = string.replace('0', '', 1)
    return string


class MyFloat(float):
    def __str__(self):
        string = super().__str__()
        return _remove_leading_zero(self, string)

    def __format__(self, format_string):
        string = super().__format__(format_string)
        return _remove_leading_zero(self, string)

使用此类,您必须使用str.format函数而不是模数运算符(%)进行格式化。以下是一些例子:

>>> print(MyFloat(.4444))
.4444

>>> print(MyFloat(-.4444))
-.4444

>>> print('some text {:.3f} some more text',format(MyFloat(.4444)))
some text .444 some more text

>>> print('some text {:+.3f} some more text',format(MyFloat(.4444)))
some text +.444 some more text

如果你还想使类的模运算符(%str以相同的方式运行,那么你必须通过继承类来重写类的__mod__方法str。但它不会像重写类的__format__方法那样容易float,因为在这种情况下,格式化的浮点数可能出现在结果字符串中的任何位置。

[注意:以上所有代码都是用Python3编写的。您还必须__unicode__在Python2中覆盖并且还必须更改super调用。]

PS:您也可以覆盖__repr__类似的方法__str__,如果您还想更改官方字符串表示形式MyFloat

编辑:实际上你可以添加新的语法来使用__format__方法格式化sting 。因此,如果您想要保持两种行为,即在需要时显示前导零,并且在不需要时不显示前导零。您可以MyFloat按如下方式创建类:

class MyFloat(float):
    def __format__(self, format_string):
        if format_string.endswith('z'):  # 'fz' is format sting for floats without leading the zero
            format_string = format_string[:-1]
            remove_leading_zero = True
        else:
            remove_leading_zero = False

        string = super(MyFloat, self).__format__(format_string)
        return _remove_leading_zero(self, string) if remove_leading_zero else string
        # `_remove_leading_zero` function is same as in the first example

并使用此类如下:

>>> print('some text {:.3f} some more text',format(MyFloat(.4444)))
some text 0.444 some more text
>>> print('some text {:.3fz} some more text',format(MyFloat(.4444)))
some text .444 some more text


>>> print('some text {:+.3f} some more text',format(MyFloat(.4444)))
some text +0.444 some more text
>>> print('some text {:+.3fz} some more text',format(MyFloat(.4444)))
some text +.444 some more text


>>> print('some text {:.3f} some more text',format(MyFloat(-.4444)))
some text -0.444 some more text
>>> print('some text {:.3fz} some more text',format(MyFloat(-.4444)))
some text -.444 some more text

请注意,使用'fz'而不是'f'会删除前导零。

此外,上面的代码适用于Python2和Python3。

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100007034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档