How can I compare the output of a type () function with a string?

2

If I have a python script like this:

texto  = "TEXTO"
cadena = "<type 'str'>"
salida = type(texto)
if(cadena == salida):
    print("Es un string")
else:
    print("No es un string")

I think in theory it's fine because you're comparing two strings but it always comes out "It's not a string" even though the strings are the same.

How can I solve it?

    
asked by Marco Leslie 11.11.2017 в 16:46
source

1 answer

3

type does not return a string, but an instance of class type . You can not therefore compare it to a string directly.

You could call your __str__ method in any case:

texto  = "TEXTO"
cadena = "<class 'str'>"      # En python 3 no es "<type 'str'>"
salida = str(type(texto))
if(type(texto) == str):
    print("Es un string")
else:
    print("No es un string")

However, this form is not "pythonic" at all and is even explicitly discouraged in PEP 8 as well as using the equality operator of the form type(a) == type(b) . A much simpler, more efficient and readable way is:

if type(cadena) is str:
    print("Es un string")
else:
    print("No es un string")
  

Warning: This only validates instances of class str , not any subclass of this. If you want to validate also any subclass you should use isinstance as recommended in PEP 8:

if isinstance(texto,  str):
    print("Es un string")
else:
    print("No es un string")
    
answered by 11.11.2017 / 17:17
source