是否有一种方法可以检查python中变量的类型是否为字符串,例如:
isinstance(x,int);
对于整数值?
是否有一种方法可以检查python中变量的类型是否为字符串,例如:
isinstance(x,int);
对于整数值?
当前回答
如果你不想依赖于外部库,这适用于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");
其他回答
我看过:
hasattr(s, 'endswith')
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程序都应该是一个很好的引用:
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。
根据下面更好的答案进行编辑。向下走大约3个答案,找出basestring的cool值。
旧的回答: 注意unicode字符串,可以从多个地方获得,包括Windows中的所有COM调用。
if isinstance(target, str) or isinstance(target, unicode):