2009-10-27 74 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的轉換器將採取主題的照顧。