Python将字符串动态转换为float或int [英] Python Convert string to float or int dynamically

查看:284
本文介绍了Python将字符串动态转换为float或int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,必须根据情况将其转换为int或float:

I have a string that I have to convert into int or float depending or the case :

What I have    => What I want
"548189848.54" => 548189848.54
"548189848.50" => 548189848.5
"548189848.00" => 548189848

有可能做到吗?

谢谢

史蒂夫

推荐答案

也许您可以转换为float然后使用round:

Maybe you could convert to float and then use round:

inputs = [ "548189848.54", "548189848.50", "548189848.00" ]

for i in inputs:
    f = float(i)
    if round(f) == f:
        print int(f)
    else:
        print f

输出:

548189848.54
548189848.5
548189848

您还可以使用列表理解来执行相同的操作,例如:

You could also do the same thing using a list comprehension, like:

print [int(float(i)) if round(float(i)) == float(i) else float(i) for i in inputs]

输出:

[548189848.54, 548189848.5, 548189848]

这篇关于Python将字符串动态转换为float或int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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