code如下:
#encoding=utf-8 print '中国' #测试一个对象是否是类字符串 print '1-------' def isAString(obj): return isinstance(obj,basestring) print isAString('abc') print isAString('abc中国') print isAString(u'abc中国') print '2-------' #bad code def isExactlyAString(anobj): return type(anobj) is type('') print isExactlyAString('abc') print isExactlyAString('abc中国') print isExactlyAString(u'abc中国') #bad occered print '3-------' #bad change bad code def isExactlyAStringNew(anobj): if type(anobj) is type(''): return True elif type(anobj) is type(u''): return True else: return False print isExactlyAStringNew('abc') print isExactlyAStringNew('abc中国') print isExactlyAStringNew(u'abc中国') #bad not occered print '4-------' def isStringLike(anobj): #better 获得时候的原谅远比事先得到许可容易的多 try: anobj + '' except: return False else:return True print isStringLike('abc') print isStringLike('abc中国') print isStringLike(u'abc中国') #bad not occered print isStringLike(1) #bad not occered
显示结果如下:
中国
1-------
True
True
True
2-------
True
True
False
3-------
True
True
True
4-------
True
True
True
False