Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

python text determines whether the object contains a class string


May 10, 2021 Python2


Table of contents


python text determines whether the object contains a class string

Scene:

Determines whether the object contains a class string

It is generally immediately expected to implement it using type().


  >>> def isExactlyAString(obj):  
      return type(obj) is type('')  
    
  >>> isExactlyAString(1)  
  False  
  >>> isExactlyAString('1')  
  True  
  >>>   

And also

  >>> def isAString(obj):  
      try :obj+''  
      except:return False  
      else:return True  
    
        
  >>> isAString(1)  
  False  
 >>> isAString('1')  
  True  
  >>> isAString({1})  
  False  
  >>> isAString(['1'])  
  False  
  >>>   

Although useless in terms of ideas and methods, we can find a better way to use python's features: isinstance (obj, str)


  >>> def isAString(obj):  
      return isinstance(obj,str)  
    
  >>> isAString(1)  
  False  
 >>> isAString('1')  
  True  
  >>>   

Str is the only string class in python3, and we can detect if the string is an instance of str