Python checks whether an object is a string type.
Purpose
Test whether an object is a string.
Method
The base class of the Python string is basestring, including the str and unicode types. Generally, the following methods can be used:
Copy codeThe Code is as follows:
Def isAString (anobj ):
Return isinstance (anobj, basestring)
However, the above method is powerless for instances of the UserString class.
Copy codeThe Code is as follows:
In [30]: B = UserString. UserString ('abc ')
In [31]: isAString (B)
Out [31]: False
In [32]: type (B)
Out [32]: <class 'userstring. userstring'>
The duck detection method commonly used in Python: If it is walking like a duck, it can be considered as a duck.
Copy codeThe Code is as follows:
Def isStringLike (anobj ):
Try:
Anobj. lower () + anobj +''
Except t:
Return False
Else:
Return True
The test results are as follows:
Copy codeThe Code is as follows:
>>> Import UserString
>>> B = UserString. UserString ('abc ')
>>> IsStringLike (B)
True
>>>
About Style
Execute the task according to your own tone. In this process, all errors and exceptions caused by non-matching are detected and handled. This processing method is called:
Copy codeThe Code is as follows:
EAFP: It's easier to ask forgiveness than permission.
Try/try t is a key tool to ensure the style.
Gossip about the UserString class
For version 2.x: as mentioned in the Python document, if versions earlier than Version 2.2 are not involved, use the str type instead of the UserString type.
For version 3.x: This module has been moved to the collection module.
There are two main methods for this class:
Copy codeThe Code is as follows:
Class UserString. UserString ([sequence])
The preceding example shows how to convert str () to str.
Copy codeThe Code is as follows:
Class UserString. MutableString ([sequence])
The string can also be changed! Look here:
Copy codeThe Code is as follows:
A = UserString. MutableString ('abc ')
A [0] = 'C'
In [10]:
Out [10]: 'cbc'
The Python document contains a line of italics. The original method is obsolete, and 3.0 is gone:
Copy codeThe Code is as follows:
Deprecated since version 2.6: The MutableString class has been removed in Python 3.0.