在字符串中将截断的Python float格式化为int [英] Format truncated Python float as int in string

查看:479
本文介绍了在字符串中将截断的Python float格式化为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  some_float = 1234.5678 
print'%02d'%some_float#1234

some_float = 1234.5678
print'{WHAT?}'。format(some_float)#我想要1234这里


$ b

注意: {:. 0f} 不是一个选项,因为它循环(返回 1235 <
$ b

format(...,int(some_float))是正是我想避免的事情,请不要这样建议。

解决方案

可以扩展标准字符串格式语言通过扩展类 string.Formatter

  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


A quick no-brainer:

some_float = 1234.5678
print '%02d' % some_float  # 1234

some_float = 1234.5678
print '{WHAT?}'.format(some_float) # I want 1234 here too

Note: {:.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.

解决方案

It's possible to extend the standard string formatting language by extending the class string.Formatter:

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"

这篇关于在字符串中将截断的Python float格式化为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆