是否有一种方法可以检查python中变量的类型是否为字符串,例如:

isinstance(x,int);

对于整数值?


当前回答

其他人在这里提供了很多很好的建议,但我没有看到一个好的跨平台总结。下面的代码对于任何Python程序都应该是一个很好的引用:

def isstring(s):
    # if we use Python 3
    if (sys.version_info[0] >= 3):
        return isinstance(s, str)
    # we use Python 2
    return isinstance(s, basestring)

在这个函数中,我们使用isinstance(object, classinfo)来查看输入是python3中的str还是python2中的basestring。

其他回答

如果检查的不是整型和字符串,类型模块也存在。 http://docs.python.org/library/types.html

我还想注意,如果你想检查一个变量的类型是否是特定的类型,你可以将变量的类型与一个已知对象的类型进行比较。

对于字符串,你可以使用这个

type(s) == type('')

Python 2 / 3,包括unicode

from __future__ import unicode_literals
from builtins import str  #  pip install future
isinstance('asdf', str)   #  True
isinstance(u'asdf', str)  #  True

http://python-future.org/overview.html

其他人在这里提供了很多很好的建议,但我没有看到一个好的跨平台总结。下面的代码对于任何Python程序都应该是一个很好的引用:

def isstring(s):
    # if we use Python 3
    if (sys.version_info[0] >= 3):
        return isinstance(s, str)
    # we use Python 2
    return isinstance(s, basestring)

在这个函数中,我们使用isinstance(object, classinfo)来查看输入是python3中的str还是python2中的basestring。

我看过:

hasattr(s, 'endswith')