牛骨文教育服务平台(让学习变的简单)

轻松python文本专题-判断对象里面是否是类字符串(推荐使用isinstance(obj,str))

场景:

判断对象里面是否是类字符串

一般立刻会想到使用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的实例

就说到这里,谢谢大家