This article mainly introduces the Python detection of whether an object is a string class method, that is, detection is an object is a string object, this article also explained an interesting method of judgment, the need for friends can refer to the
Objective
Test whether an object is a string
Method
The base class for Python strings is basestring, which includes STR and Unicode types. You can generally use the following methods:
The code is as follows:
def isastring (anobj):
Return Isinstance (anobj,basestring)
However, the above methods for the UserString class of examples, powerless.
The code is as follows:
In [m]: b=userstring.userstring (' abc ')
In [to]: isastring (b)
OUT[31]: False
In [i]: type (b)
OUT[32]:
The duck Judge method commonly used in Python: if it walks like a duck and barks like a duck, it can be considered a duck.
The code is as follows:
def isstringlike (anobj):
Try
Anobj.lower () + Anobj + '
Except
Return False
Else
Return True
The test results are as follows:
The code is as follows:
>>> Import userstring
>>> b=userstring.userstring (' abc ')
>>> Isstringlike (b)
True
>>>
About Style
Perform the task in its own tone, detecting and handling all errors and exceptions generated by the mismatch during this process. This approach is called:
The code is as follows:
Eafp:it ' s easier to ask forgiveness than permission.
Try/except is the key tool to ensure this style.
Gossip about the UserString class
for 2. X version: The Python document mentions that if you do not refer to a previous version of 2.2, consider using the STR type directly instead of the userstring type.
For 3. X version: The module has been moved to the collection module.
There are two main methods of this class:
The code is as follows:
Class userstring.userstring ([sequence])
Use the previous example already, note that you can use STR () to convert to STR type
The code is as follows:
Class userstring.mutablestring ([sequence])
Strings can also change Oh! Look here:
The code is as follows:
A=userstring.mutablestring (' abc ')
A[0]= ' C '
In [ten]: a
OUT[10]: ' CBC '
The Python document has a line in bold, which is already a deprecated method, and 3.0 is gone:
The code is as follows:
Deprecated since version 2.6:the mutablestring class has been removed in Python 3.0.