是否有一种方法可以检查python中变量的类型是否为字符串,例如:

isinstance(x,int);

对于整数值?


当前回答

您可以简单地使用isinstance函数来确保输入数据的格式为字符串或unicode。下面的例子会帮助你更容易理解。

>>> isinstance('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string',  unicode)
True

其他回答

你可以:

var = 1
if type(var) == int:
   print('your variable is an integer')

or:

var2 = 'this is variable #2'
if type(var2) == str:
    print('your variable is a string')
else:
    print('your variable IS NOT a string')

希望这能有所帮助!

So,

你有很多选项来检查你的变量是否是字符串:

a = "my string"
type(a) == str # first 
a.__class__ == str # second
isinstance(a, str) # third
str(a) == a # forth
type(a) == type('') # fifth

这个命令是有目的的。

根据下面更好的答案进行编辑。向下走大约3个答案,找出basestring的cool值。

旧的回答: 注意unicode字符串,可以从多个地方获得,包括Windows中的所有COM调用。

if isinstance(target, str) or isinstance(target, unicode):

使用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))

输出:

真正的 假 真正的 假

如果检查的不是整型和字符串,类型模块也存在。 http://docs.python.org/library/types.html