是否有一种方法可以检查python中变量的类型是否为字符串,例如:
isinstance(x,int);
对于整数值?
是否有一种方法可以检查python中变量的类型是否为字符串,例如:
isinstance(x,int);
对于整数值?
当前回答
我知道这是一个老话题,但作为谷歌上的第一个,鉴于我对任何一个答案都不满意,我将把这个留在这里供将来参考:
six是一个Python 2和3兼容性库,已经涵盖了这个问题。然后你可以这样做:
import six
if isinstance(value, six.string_types):
pass # It's a string !!
检查代码,如下所示:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
else:
string_types = basestring,
其他回答
其他人在这里提供了很多很好的建议,但我没有看到一个好的跨平台总结。下面的代码对于任何Python程序都应该是一个很好的引用:
def isstring(s):
# if we use Python 3
if (sys.version_info[0] >= 3):
return isinstance(s, str)
# we use Python 2
return isinstance(s, basestring)
在这个函数中,我们使用isinstance(object, classinfo)来查看输入是python3中的str还是python2中的basestring。
我还想注意,如果你想检查一个变量的类型是否是特定的类型,你可以将变量的类型与一个已知对象的类型进行比较。
对于字符串,你可以使用这个
type(s) == type('')
总结:
如果你既想要Python2又想要Python3,并且还想要包含unicode,似乎没有一种可移植的方法来做到这一点。我最后用了这个习语:
# Near the top of my program
if sys.version_info[0] >= 3:
basestring = str
然后,任何时候我想测试一个对象,看看它是否是字符串:
if isinstance(obj, basestring):
...
坦率地说,Python3删除了basestring和types.StringTypes,这让我有点震惊。我认为没有理由放弃他们,留下他们中的任何一个都会使这个问题得到解决。
如果你不想依赖于外部库,这适用于Python 2.7+和Python 3 (http://ideone.com/uB4Kdc):
# your code goes here
s = ["test"];
#s = "test";
isString = False;
if(isinstance(s, str)):
isString = True;
try:
if(isinstance(s, basestring)):
isString = True;
except NameError:
pass;
if(isString):
print("String");
else:
print("Not String");
使用type()或isinstance()
我不知道为什么在我面前没有一个答案包含这个简单的类型(my_variable)是str语法,但使用type()这样似乎是最符合逻辑和最简单的,到目前为止:
(在Python3中测试):
# Option 1: check to see if `my_variable` is of type `str`
type(my_variable) is str
# Option 2: check to see if `my_variable` is of type `str`, including
# being a subclass of type `str` (ie: also see if `my_variable` is any object
# which inherits from `str` as a parent class)
isinstance(my_variable, str)
Python type()内置函数文档在这里:https://docs.python.org/3/library/functions.html#type。它的部分内容如下。注意关于isinstance()的说明:
类类型(对象) 类类型(名称,基础,字典,**kwds) 使用一个参数,返回对象的类型。返回值是一个类型对象,通常与object.__class__返回的对象相同。 建议使用isinstance()内置函数测试对象的类型,因为它考虑了子类。
因此,如果检查的是类对象而不是简单变量的类型,并且需要考虑子类,则使用isinstance()代替。请在这里查看其文档:https://docs.python.org/3/library/functions.html#isinstance。
示例代码:
my_str = "hello"
my_int = 7
print(type(my_str) is str)
print(type(my_int) is str)
print()
print(isinstance(my_str, str))
print(isinstance(my_int, str))
输出:
真正的 假 真正的 假