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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:44:50  来源:igfitidea点击:

Difference in python between basestring and types.StringType?

python

提问by YGA

What's the difference between:

有什么区别:

isinstance(foo, types.StringType)

and

isinstance(foo, basestring)

?

?

回答by Luká? Lalinsky

For Python2: basestringis the base class for both strand unicode, while types.StringTypeisstr. If you want to check if something is a string, use basestring. If you want to check if something is a bytestring, use strand forget about types.

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

回答by John La Rooy

This stuff is completely different in Python3

这个东西在Python3中完全不同

typesnot longer has StringType
stris always unicode
basestringno longer exists

types不再有StringType
str总是unicode
basestring不再存在

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 转换器会处理这个话题。