W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
場景:
判斷對象里面是否是類字符串
一般立刻會想到使用 type() 來實現
>>> def isExactlyAString(obj):
return type(obj) is type('')
>>> isExactlyAString(1)
False
>>> isExactlyAString('1')
True
>>>
還有
>>> def isAString(obj):
try :obj+''
except:return False
else:return True
>>> isAString(1)
False
>>> isAString('1')
True
>>> isAString({1})
False
>>> isAString(['1'])
False
>>>
雖然思路上和方法使用上都沒用問題,但是如果從 python 的特性出發(fā),我們可以找到更好的方法:isinstance(obj, str)
>>> def isAString(obj):
return isinstance(obj,str)
>>> isAString(1)
False
>>> isAString('1')
True
>>>
str 作為 python3 里面唯一的一個字符串類,我們可以檢測字符串是否是 str 的實例
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯系方式:
更多建議: