command to be able to compare between a string and an integer in Python (as a condition)

0

I have a question, how can I compare between string and integer in Python? I want that if my data entered is a string, give me a message and if it is an int that my code continues.

Code that I tried:

n=raw_input("ingrese numero jugadores: ") if str==str(int): 
print("escribe un numero, no una letra")
    
asked by VICENTE DANIEL PALACIOS 16.04.2017 в 16:04
source

4 answers

0
If str == str(int):

In short, you can string the whole

    
answered by 16.04.2017 / 16:29
source
2

You can use the function raw_input , with it check if what you have entered is an integer and then continue with your idea.

while True:
n=raw_input("ingrese numero jugadores: ") 
   try: 
     n=int(n)
     return n

   except ValueError:

      print "Escribe un numero, no una letra."

Another option is to directly check the type:

if type(n) !=int:
    raise TypeError, "Escriba un numero"
    
answered by 16.04.2017 в 16:55
1

Your question is a bit ambiguous, but I think what you are trying to do is to compare if a string is the representation of a whole number, if so, what can be done is this:

def is_int(s):
    try:
        return int(s)
    except ValueError:
        return False


if not is_int('hola'):
    print('Es una cadena de caracteres no un entero')

if not is_int('14'):
    print('Es una cadena de caracteres no un entero')
    
answered by 16.04.2017 в 17:06
1

Based on what I understood your question, I have two interpretations

Assuming that the data entered is a string (from an input for example) ... and you want to check if they contain integers, you could do something like this:

entrada=input(">>")
if not entrada.isdigit():
    print("Por favor usa solo números enteros")
else:
    entero=int(entrada)
    #Continuar la ejecución del código

In case you refer to a variable and want to check its type:

entrada="15" # un string
if type(entrada)==str:
    print("no admito strings")
elif type(entrada)==int:
    #operaciones con el entero
    #Continuar con la ejecución del código

In the case of the latter, it will not accept data such as "15", but the first example would do so.

I hope I have helped.

    
answered by 16.04.2017 в 17:19