本文介紹了Python,確定字符串是否應轉換為 Int 或 Float的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想將字符串轉換為最緊湊的數(shù)據(jù)類型:int 或 float.
I want to convert a string to the tightest possible datatype: int or float.
我有兩個字符串:
value1="0.80" #this needs to be a float
value2="1.00" #this needs to be an integer.
如何確定在 Python 中 value1 應該是 Float 而 value2 應該是 Integer?
How I can determine that value1 should be Float and value2 should be Integer in Python?
推薦答案
def isfloat(x):
try:
a = float(x)
except (TypeError, ValueError):
return False
else:
return True
def isint(x):
try:
a = float(x)
b = int(a)
except (TypeError, ValueError):
return False
else:
return a == b
這篇關于Python,確定字符串是否應轉換為 Int 或 Float的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!