Search code examples
pythonraw-inputtld

Python code to determine if TLD exists, prompt again if not?


This is an additional question in regards to this post: Python raw_input with forced TLD?

I have a check in place to see if a string ends with a TLD,

TLD = ('.com', '.info', '.org', '.net')
if raw_input("Please enter a hostname").endswith(TLD):
# blah blah

But I am attempting to store the raw_input in to a variable. Would the proper coding practice be to do something such as:

TLD = ('.com', '.info', '.org', '.net')
hostName = raw_input(":").lower()
<<piece of code that determines if hostName does in fact end with a TLD?>>

If so, what would that look like? I attempted a while True: and an if elif statement but I am not getting anywhere, I have googled endlessly with no results which is why I post this question here.

The program in question will grab the hostname, say google.com, determine if it has a valid TLD, strip the TLD off of hostName and store it in hostNameshort (both will be used later), if it doesn't get a proper TLD prompt again with emphasis on that it needs the TLD during input time, and then continue on once it does.


Solution

  • Something like this:

    TLD = ('.com', '.info', '.org', '.net')
    hostName = raw_input(":").lower()
    while not hostName.endswith(TLD):
        print "Incorrect input, Try again!"
        hostName = raw_input(":").lower()
    

    Demo:

    :foo.bar
    Incorrect input, Try again!
    :google.in
    Incorrect input, Try again!
    :yahoo.com