是否有一种方法可以检查python中变量的类型是否为字符串,例如:
isinstance(x,int);
对于整数值?
是否有一种方法可以检查python中变量的类型是否为字符串,例如:
isinstance(x,int);
对于整数值?
当前回答
So,
你有很多选项来检查你的变量是否是字符串:
a = "my string"
type(a) == str # first
a.__class__ == str # second
isinstance(a, str) # third
str(a) == a # forth
type(a) == type('') # fifth
这个命令是有目的的。
其他回答
我是这样做的:
if type(x) == type(str()):
如果你不想依赖于外部库,这适用于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");
a = '1000' # also tested for 'abc100', 'a100bc', '100abc'
isinstance(a, str) or isinstance(a, unicode)
返回True
type(a) in [str, unicode]
返回True
Python 2的另一种方法,不使用basestring:
isinstance(s, (str, unicode))
但仍然不能在Python 3中工作,因为unicode没有定义(在Python 3中)。
如果检查的不是整型和字符串,类型模块也存在。 http://docs.python.org/library/types.html