2009-10-27 76 views

回答

17

对于Python2:basestring对于两个strunicode基类,而types.StringTypestr。如果你想检查是否有字符串,请使用basestring。如果你想检查是否有字节串,请使用str,忘记types

10

这东西是在Python3完全不同

types不再有StringType
str始终是unicode的
basestring不再存在

所以尽量不要洒的东西通过您的代码,如果你太多可能需要将其端口

1
>>> import types 
>>> isinstance(u'ciao', types.StringType) 
False 
>>> isinstance(u'ciao', basestring) 
True 
>>> 

相当重要的区别,在我看来;-)。

0

对于Python 2.x的:

try: 
    basestring  # added in Python 2.3 
except NameError: 
    basestring = (str, unicode) 
... 
if isinstance(foo, basestring): 
    ... 

当然这可能不是为Python 3工作,但我敢肯定的2to3的转换器将采取主题的照顾。