python 中 basestring 和 types.StringType 的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1633082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference in python between basestring and types.StringType?
提问by YGA
What's the difference between:
有什么区别:
isinstance(foo, types.StringType)
and
和
isinstance(foo, basestring)
?
?
回答by Luká? Lalinsky
For Python2: basestring
is the base class for both str
and unicode
, while types.StringType
isstr
. If you want to check if something is a string, use basestring
. If you want to check if something is a bytestring, use str
and forget about types
.
对于Python2:basestring
是两个基类str
和unicode
,而types.StringType
为str
。如果你想检查某个东西是否是一个字符串,请使用basestring
. 如果您想检查某个东西是否是字节串,请使用str
并忘记types
.
回答by John La Rooy
This stuff is completely different in Python3
这个东西在Python3中完全不同
types
not longer has StringType
str
is always unicodebasestring
no longer exists
types
不再有StringType
str
总是unicodebasestring
不再存在
So try not to sprinkle that stuff through your code too much if you might ever need to port it
因此,如果您可能需要移植它,请尽量不要在您的代码中过多地撒播这些东西
回答by Alex Martelli
>>> import types
>>> isinstance(u'ciao', types.StringType)
False
>>> isinstance(u'ciao', basestring)
True
>>>
Pretty important difference, it seems to me;-).
非常重要的区别,在我看来;-)。
回答by Tobias
For Python 2.x:
对于 Python 2.x:
try:
basestring # added in Python 2.3
except NameError:
basestring = (str, unicode)
...
if isinstance(foo, basestring):
...
Of course this might not work for Python 3, but I'm quite sure the 2to3 converter will take care of the topic.
当然,这可能不适用于 Python 3,但我很确定 2to3 转换器会处理这个话题。