如何检查是否可以将字符串类型转换为在Python中浮动? [英] How to check whether string might be type-cast to float in Python?

查看:191
本文介绍了如何检查是否可以将字符串类型转换为在Python中浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有像 str.isnumeric 这样的函数,但是适用于float?

  '13 .37'.isnumeric()#False 

我还是用这个:

  def isFloat(string):
试试:
float(string)
return True
除了ValueError:
返回False


解决方案

正如Imran所说,你的代码是绝对正常的。鼓励客户将 isFloat 放在前进之路的路径下,而不是更多的Pythonic容易要求宽恕而不是权限的路径。



对于客户来说,假设他们有一个代表一个浮点数的字符串,但是准备好处理如果不是这样的异常,这种方法也有很好的副作用,将字符串转换为一次浮动而不是两次。


Is there some function like str.isnumeric but applicable to float?

'13.37'.isnumeric() #False  

I still use this:

def isFloat(string):
    try:
        float(string)
        return True
    except ValueError:
        return False

解决方案

As Imran says, your code is absolutely fine as shown.

However, it does encourage clients of isFloat down the "Look Before You Leap" path instead of the more Pythonic "Easier to Ask Forgiveness than Permission" path.

It's more Pythonic for clients to assume they have a string representing a float but be ready to handle the exception that will be thrown if it isn't.

This approach also has the nice side-effect of converting the string to a float once instead of twice.

这篇关于如何检查是否可以将字符串类型转换为在Python中浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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