在上一篇博客(python2 type()函数 isinstance()函数,网址:http://blog.csdn.net/sxingming/article/details/51318939)中,我们学习了isinstance()函数的使用,在此基础上,本文介绍python 2 中的basestring()函数的使用。
basestring是str和unicode的超类(父类),是抽象类(The basestring type cannot be instantiated),不能被调用和实例化,但可以用来判断一个对象是否为str或者unicode的实例,
isinstance(obj, basestring)等价于isinstance(obj, (str, unicode));
python2.3版本以后引入该函数,兼容python2.3以后python2各版本。但是python3舍弃了该函数,所以该函数不能在python3中使用。
>>> type('hello python')
<type 'str'>
>>> isinstance('hello python',str)
True
>>> isinstance('hello python',basestring)
True
>>> type(u'哈喽')
<type 'unicode'>
>>> isinstance(u'哈喽',unicode)
True
>>> isinstance(u'哈喽',basestring)
True
>>> type(u'hello python')
<type 'unicode'>
>>> isinstance(u'hello python',unicode)
True
>>> isinstance(u'hello python',basestring)
True