在字符串中将截断的Python float格式化为int [英] Format truncated Python float as int in string
问题描述
some_float = 1234.5678
print'%02d'%some_float#1234
some_float = 1234.5678
print'{WHAT?}'。format(some_float)#我想要1234这里
$ b
注意: 可以扩展标准字符串格式语言通过扩展类 string.Formatter : A quick no-brainer: Note: It's possible to extend the standard string formatting language by extending the class string.Formatter:
这篇关于在字符串中将截断的Python float格式化为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! {:. 0f}
不是一个选项,因为它循环(返回 1235 <
$ b format(...,int(some_float))
是正是我想避免的事情,请不要这样建议。
class MyFormatter(Formatter):
def format_field(self,value,format_spec):
if format_spec =='t':#截断渲染为int
return str(int(value))
return super(MyFormatter,self).format_fi eld(value,format_spec)
MyFormatter()。format({0} {1:t},Hello,4.567)#返回Hello 4
some_float = 1234.5678
print '%02d' % some_float # 1234
some_float = 1234.5678
print '{WHAT?}'.format(some_float) # I want 1234 here too
{:.0f}
is not an option, because it rounds (returns 1235
in this example).format(..., int(some_float))
is exactly the thing I'm trying to avoid, please don't suggest that.class MyFormatter(Formatter):
def format_field(self, value, format_spec):
if format_spec == 't': # Truncate and render as int
return str(int(value))
return super(MyFormatter, self).format_field(value, format_spec)
MyFormatter().format("{0} {1:t}", "Hello", 4.567) # returns "Hello 4"