python文本 判斷對象裏面是否是類字符串
阿新 • • 發佈:2018-01-26
log 場景 是否 text 但是 normal line -c ring
python文本 判斷對象裏面是否是類字符串
場景:
判斷對象裏面是否是類字符串
一般立刻會想到使用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的特性出發,我們可以找到更好的方法:isinstance(obj,str)
>>> def isAString(obj):
return isinstance(obj,str)
>>> isAString(1)
False
>>> isAString(‘1‘)
True
>>>
str作為python3裏面唯一的一個字符串類,我們可以檢測字符串是否是str的實例
python文本 判斷對象裏面是否是類字符串