是否有一种方法可以检查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。

其他回答

因为在Python3中没有定义basestring,这个小技巧可能有助于使代码兼容:

try: # check whether python knows about 'basestring'
   basestring
except NameError: # no, it doesn't (it's Python3); use 'str' instead
   basestring=str

之后,您可以在Python2和Python3上运行以下测试

isinstance(myvar, basestring)

如果你不想依赖于外部库,这适用于Python 2.7+和Python 3 (http://ideone.com/uB4Kdc):

# your code goes here
s = ["test"];
#s = "test";
isString = False;

if(isinstance(s, str)):
    isString = True;
try:
    if(isinstance(s, basestring)):
        isString = True;
except NameError:
    pass;

if(isString):
    print("String");
else:
    print("Not String");

总结:

如果你既想要Python2又想要Python3,并且还想要包含unicode,似乎没有一种可移植的方法来做到这一点。我最后用了这个习语:

# Near the top of my program
if sys.version_info[0] >= 3:
    basestring = str

然后,任何时候我想测试一个对象,看看它是否是字符串:

if isinstance(obj, basestring):
    ...

坦率地说,Python3删除了basestring和types.StringTypes,这让我有点震惊。我认为没有理由放弃他们,留下他们中的任何一个都会使这个问题得到解决。

>>> thing = 'foo'
>>> type(thing).__name__ == 'str' or type(thing).__name__ == 'unicode'
True

我是这样做的:

if type(x) == type(str()):