簡體   English   中英

是否有內置方法來檢查字符串是否可以轉換為浮點數?

[英]Is there built-in way to check if string can be converted to float?

我知道有一些方法可以檢查 str 是否可以使用 try-except 或正則表達式進行轉換,但我一直在尋找(例如) str 方法,例如

str.isnumeric()
str.isdigit()
str.isdecimal() # also doesn't work for floats

但找不到任何。 有沒有我還沒有找到的?

我建議使用 try except 子句的請求寬恕而不是許可方法:

str_a = 'foo'
str_b = '1.2'

def make_float(s):
    try:
        return float(s)
    except ValueError:
        return f'Can't make float of "{s}"'

>>> make_float(str_a)
Can't make float of "foo"
>>> make_float(str_b)
1.2

正如MacattackJab 所述,您可以使用try except ,您可以在python 的文檔w3school 的教程中閱讀有關內容。

Try except 子句具有以下形式:

try:
    # write your code
    pass
except Exception as e: # which can be ValueError, or other's exceptions
    # deal with Exception, and it can be called using the variable e
    print(f"Exception was {e}") # python >= 3.7
    pass
except Exception as e: # for dealing with other Exception
    pass
# ... as many exceptions you would need to handle
finally:
    # do something after dealing with the Exception
    pass

有關內置異常的列表,請參閱python 的文檔

最簡單的方法是嘗試將其變成浮動。

try:
    float(str)
except ValueError:
    # not float
else:
    # is float

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM