如何知道一个变量是一个元组,一个字符串还是一个整数?

我试图找出一个类型不匹配,同时添加一个字符串到另一个字符串在连接操作。

基本上返回的错误是一个 TypeError(不能连接字符串和元组) ; 所以我想弄清楚在哪里我分配了一个值作为元组而不是字符串。

我分配的所有值都是字符串所以我得弄清楚元组是从哪里来的所以我希望在 Python 中有一种方法可以找出变量中包含的内容以及它的类型。

到目前为止,使用 PDB我能够检查变量的内容,并且我能够正确地得到我所期望的值; 但是我也想知道变量的类型(通过逻辑,如果编译器能够引发类型错误,这意味着它知道变量内部是什么以及它是否与要执行的操作兼容; 所以必须有一种方法来获得那个值/标志)。

有没有办法打印出 Python 中变量的类型?

顺便说一句,我试图将所有变量都改为显式字符串,但是强制 str (myvar)是不可行的,所以我不能在使用字符串的任何地方都将其强制转换为字符串类型。

105635 次浏览

You just use:

type(varname)

which will output int, str, float, etc...

make use of isinstance ?

if isinstance(var, int):


if isinstance(var, str):


if isinstance(var, tuple):

You probably want to test (assuming Python 2.x) using isinstance(obj, basestring). You have the options of using isinstance, type, and calling the attribute __class__, but isinstance is likely to be the one you want here. Take a look at this article for a more thorough treatment of the differences between the three options.

isinstance(obj, tuple)
isinstance(obj, basestring)
isinstance(obj, int)

repr(object) will give a textual description of object, which should show type and value. Your can print or view this in the debugger.

For simple values repr usually returns the same string as you would write the value literally in code. For custom classes it gives the class name and object id, or something else if the class'es

__repr__

is overridden.

Please note, should you wanted to check your var type in if statement, the construct if type(varname) == "tuple": won't work. But these will:

if type(varname) is tuple:
if type(varname) is list:
if type(varname) is dict:
if type(varname) is int:
if type(varname) is str:

To complement Goujon's answer consider this list of mixed integers and tuples:

for f in fills:
print (type(f), f)
if type(f)==int : print "INTEGER!!!"

Generates this output:

(<type 'int'>, 0)
INTEGER!!!
(<type 'tuple'>, (62973, 39058, 25708, 102))
(<type 'int'>, 1)
INTEGER!!!
(<type 'tuple'>, (16968, 12069, 3329, 102))
(<type 'int'>, 2)
INTEGER!!!
(<type 'tuple'>, (24939, 62205, 30062, 102))
(<type 'tuple'>, (32911, 32911, 0, 153))
(<type 'tuple'>, (32911, 0, 0, 153))
(<type 'tuple'>, (32911, 0, 32911, 153))
(<type 'tuple'>, (65535, 0, 0, 153))
(<type 'tuple'>, (0, 0, 65535, 153))
(<type 'tuple'>, (0, 32911, 0, 153))
(<type 'tuple'>, (0, 65535, 65535, 153))

So the secret isn't to test for "int" character string but, rather test for int keyword instead. If you are like me and migrating from the Bash scripting world, using == tests in the Python scripting world will probably be your first step.