尝试使用格式说明符来打印一个小于1而没有前导零的浮点数。我想出了一些黑客,但我认为有一种方法可以在格式说明符中删除前导零。我在文档中找不到它。
问题
>>> k = .1337
>>> print "%.4f" % k
'0.1337'
劈
>>> print ("%.4f" % k) [1:]
'.1337'
发布于 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。
发布于 2019-06-21 13:41:28
一个可行的选项,没有正则表达式,负数大于10
k = -.1337
("%.4f" % k).replace("-0","-").lstrip("0")
https://stackoverflow.com/questions/-100007034
复制相似问题