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")