问题:如何检查变量是否为具有python 2和3兼容性的字符串
我知道我可以isinstance(x, str)
在python-3.x中使用:但我还需要检查python-2.x中是否还有字符串。会isinstance(x, str)
按预期在python-2.x的?还是我需要检查版本并使用isinstance(x, basestr)
?
具体来说,在python-2.x中:
>>>isinstance(u"test", str)
False
和python-3.x没有 u"foo"
I’m aware that I can use: isinstance(x, str)
in python-3.x but I need to check if something is a string in python-2.x as well. Will isinstance(x, str)
work as expected in python-2.x? Or will I need to check the version and use isinstance(x, basestr)
?
Specifically, in python-2.x:
>>>isinstance(u"test", str)
False
and python-3.x does not have u"foo"
回答 0
如果要编写兼容2.x和3.x的代码,则可能要使用六个:
from six import string_types
isinstance(s, string_types)
If you’re writing 2.x-and-3.x-compatible code, you’ll probably want to use six:
from six import string_types
isinstance(s, string_types)
回答 1
我发现不依赖六个软件包的最简洁的方法是:
try:
basestring
except NameError:
basestring = str
然后,假设您以最通用的方式检查了Python 2中的字符串,
isinstance(s, basestring)
现在也将适用于Python 3+。
The most terse approach I’ve found without relying on packages like six, is:
try:
basestring
except NameError:
basestring = str
then, assuming you’ve been checking for strings in Python 2 in the most generic manner,
isinstance(s, basestring)
will now also work for Python 3+.
回答 2
那在所有情况下都可行吗?
isinstance(x, ("".__class__, u"".__class__))
What about this, works in all cases?
isinstance(x, ("".__class__, u"".__class__))
回答 3
这是@Lev Levitsky的答案,重写了一下。
try:
isinstance("", basestring)
def isstr(s):
return isinstance(s, basestring)
except NameError:
def isstr(s):
return isinstance(s, str)
该try
/ except
测试只进行一次,然后定义总是工作,并尽可能快的功能。
编辑:实际上,我们甚至不需要调用isinstance()
;我们只需要评估一下basestring
,看看是否得到NameError
:
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
except NameError:
def isstr(s):
return isinstance(s, str)
我认为,调用会更容易isinstance()
。
This is @Lev Levitsky’s answer, re-written a bit.
try:
isinstance("", basestring)
def isstr(s):
return isinstance(s, basestring)
except NameError:
def isstr(s):
return isinstance(s, str)
The try
/except
test is done once, and then defines a function that always works and is as fast as possible.
EDIT: Actually, we don’t even need to call isinstance()
; we just need to evaluate basestring
and see if we get a NameError
:
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
except NameError:
def isstr(s):
return isinstance(s, str)
I think it is easier to follow with the call to isinstance()
, though.
回答 4
该future
库添加了(兼容 Python 2)兼容名称,因此您可以继续编写Python 3。您可以简单地执行以下操作:
from builtins import str
isinstance(x, str)
要安装它,只需执行pip install future
。
作为一个警告,它仅支持python>=2.6
,>=3.3
但它是更现代的比six
,这是唯一的建议,如果使用python 2.5
The future
library adds (to Python 2) compatible names, so you can continue writing Python 3. You can simple do the following:
from builtins import str
isinstance(x, str)
To install it, just execute pip install future
.
As a caveat, it only support python>=2.6
,>=3.3
, but it is more modern than six
, which is only recommended if using python 2.5
回答 5
也许使用类似的解决方法
def isstr(s):
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
Maybe use a workaround like
def isstr(s):
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
回答 6
您可以通过调用来获取对象的类object.__class__
,以便检查object是否为默认字符串类型:
isinstance(object,"".__class__)
而且您可以将以下内容放在代码的顶部,以便用引号括起来的字符串在python 2中的unicode中:
from __future__ import unicode_literals
You can get the class of an object by calling object.__class__
, so in order to check if object is the default string type:
isinstance(object,"".__class__)
And You can place the following in the top of Your code so that strings enclosed by quotes are in unicode in python 2:
from __future__ import unicode_literals
回答 7
您可以在代码的开头尝试此操作:
from __future__ import print_function
import sys
if sys.version[0] == "2":
py3 = False
else:
py3 = True
if py3:
basstring = str
else:
basstring = basestring
然后在代码中:
anystring = "test"
# anystring = 1
if isinstance(anystring, basstring):
print("This is a string")
else:
print("No string")
You can try this at the beginning of your code:
from __future__ import print_function
import sys
if sys.version[0] == "2":
py3 = False
else:
py3 = True
if py3:
basstring = str
else:
basstring = basestring
and later in the code:
anystring = "test"
# anystring = 1
if isinstance(anystring, basstring):
print("This is a string")
else:
print("No string")
回答 8
小心!在Python 2,str
并且bytes
基本上是相同的。如果您试图区分两者,则可能会导致错误。
>>> size = 5
>>> byte_arr = bytes(size)
>>> isinstance(byte_arr, bytes)
True
>>> isinstance(byte_arr, str)
True
Be careful! In python 2, str
and bytes
are essentially the same. This can cause a bug if you are trying to distinguish between the two.
>>> size = 5
>>> byte_arr = bytes(size)
>>> isinstance(byte_arr, bytes)
True
>>> isinstance(byte_arr, str)
True
回答 9
类型(字符串)== str
如果它是一个字符串,则返回true;否则,则返回false
type(string) == str
returns true if its a string, and false if not