Search for words within another

2

I want to know if you have entered a domain or an ip.

I have already tried several things:

addr = raw_input('Introduce la ip o el nombre de dominio: ')

addrs= [".com", ".es"]

if addr in addrs:
    print "es un dominio"

else:
    print "es una ip"

Also:

if addr == ".com" or ".es"

And some more that has occurred to me. I am very new to programming, but I need to solve the doubt to learn. How could I do what I want?

    
asked by Mike 24.02.2017 в 19:30
source

3 answers

3

An idea, python has many functions for version 2.7 you should take a look at its documentation so you know which ones exist.

For example, the find

method
cadena = "[email protected]"
dominios = ["gmail","hotmail"]
bandera = False # asume que no es un proveedor 

for proveedor in dominios :
    if (cadena.find(proveedor,0,len(cadena)) > 0):
       bandera = True

if(bandera):
    print "es un proveedor"
else:
    print "es un dominio" # Hacen falta más validaciones
    
answered by 24.02.2017 в 20:15
0

Why you miss what you have : if you have it now, you are trying to check if the whole string is in addrs (that is, if it is ".com" or ".es" ), when what you really want to do is check if those chains are contained within the string entered by the user.

How you can fix it : to search for substrings you can use find , a function that detects if one string contains another, and that it will return the position of the first occurrence of the searched substring, or -1 if it was not found.

Then for what you want to do:

  • Create a variable that will indicate if the substring was found and initializes to false.
  • Create a loop that traverses the values of addrs and check if they are in the string entered by the user
  • If they are, change the variable from point 1 to true
  • The code could be something like this ( and you can see it running here ):

    addr = raw_input('Introduce la ip o el nombre de dominio: ')
    addrs= [".com", ".es"]
    encontrado = False
    
    for valor in addrs :
        if addr.find(valor) > -1 :
            encontrado = True
    
    
    if encontrado :
        print "es un dominio"
    else:
        print "es una ip"
    

    Although as indicated by Toledano in a comment , another option ( more effective, of course) would be to create a regular expression that detects if the string is an IP and act accordingly.

        
    answered by 24.02.2017 в 20:19
    0

    Hi, I think it's easier that way.

    the ip is a number and a domain are letters try the following

    cad=input ('Introduce la ip o el nombre de dominio: ')
    
    try:
        aux=int(cad)
        print (cad, ": es una ip")
    
    except:
       print (cad, ":es un dominio")
    
        
    answered by 04.03.2017 в 18:17