亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

PHP
GCT1015 2023-11-09 16:47:30
我知道有一些方法可以檢查 str 是否可以使用 try- except 或正則表達式進行轉換,但我一直在尋找(例如) str 方法,例如str.isnumeric()str.isdigit()str.isdecimal() # also doesn't work for floats但找不到任何。還有我還沒找到的嗎?
查看完整描述

3 回答

?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

我建議使用 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


查看完整回答
反對 回復 2023-11-09
?
www說

TA貢獻1775條經驗 獲得超8個贊

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



查看完整回答
反對 回復 2023-11-09
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

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


try:

    float(str)

except ValueError:

    # not float

else:

    # is float


查看完整回答
反對 回復 2023-11-09
  • 3 回答
  • 0 關注
  • 172 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號