Sometimes you need to test an object, especially if you write a function or a method, you need to test whether the passed argument is a string (or if the object behaves like a string):
The following approach is to use the built-in isinstance and basestring to quickly and easily check whether an object is a string or Unicode object, as follows:
We might first reflect the type test using the Type method:
def isastring (anobj): return type (anobj) is type (") is not pythonic in this way, and Unicode objects cannot pass detection. The first detection method is much better, built into Basestring is the STR and Unicode type to the common base class, any class string custom type should be derived from basestring, so as to ensure that the isinstance work properly. However, the Isinstance method is not 100% perfect detection scheme, for the userstring module in the Python standard library to the UserString class to the instance, cannot pass the detection. The UserString object is an obvious class-string object because it is not derived from basestring. If you want to support this type of detection, you can directly check whether an object behaves like a string, for example:
def isstringlike (anobj): try: anobj+ ' Except:return False return True
This method is much slower than the isastring function, but detection for userstring is also suitable for STR and Unicode.
Summary: The usual type checking method in Python is the so-called duck judgment: if it walks like a duck and cries like a duck, then for us it is a duck.
Tests whether an object is a class string