How to check if type of a variable is string?

Is there a way to check if the type of a variable in python is string.. like

isinstance(x,int);

for integer values?


In Python 2.x, you would do

isinstance(s, basestring)

basestring is the abstract superclass of str and unicode . It can be used to test whether an object is an instance of str or unicode .


In Python 3.x, the correct test is

isinstance(s, str)

The bytes class isn't considered a string type in Python 3.


I know this is an old topic, but being the first one shown on google and given that I don't find any of the answers satisfactory, I'll leave this here for future reference:

six is a Python 2 and 3 compatibility library which already covers this issue. You can then do something like this:

import six

if isinstance(value, six.string_types):
    pass # It's a string !!

Inspecting the code, this is what you find:

import sys

PY3 = sys.version_info[0] == 3

if PY3:
    string_types = str,
else:
    string_types = basestring,

在Python 3.x或Python 2.7.6中

if type(x) == str:
链接地址: http://www.djcxy.com/p/85316.html

上一篇: 内部源代码文档

下一篇: 如何检查变量的类型是否是字符串?