Anlact Huynh
Anlact Huynh

Reputation: 33

How can you validate a string properly?

Currently I have a piece of code that will allow me to check if the name is true or false. However, if I add a space or another letter in the string, it will still count it as correct. So if I change it to johndoe, since it still has the string "John" it will return true.

def bouncer():
    myname = ["john"]

    for word in myname:
        if "john" not in myname:
            print(False)
    
        if "john" in myname:
            print(True)

bouncer()

Upvotes: 0

Views: 63

Answers (1)

TheEagle
TheEagle

Reputation: 5992

You are never using the word variable from the for loop, instead you are checking whether the string "john" is exactly contained in the array mylist. If you want to to do what you described in your text, the code should be like this:

def compare(name1, name2):
    print(name1 == name2)

compare("john", "john") # prints True
compare("john", "johndoe") # prints False

But if you want to check whether the name is exactly contained in a list of names, it should be like this:

def compare(names, name):
    print(name in names)
compare(["anna", "bob", "john"], "john") # prints True
compare(["anna", "bob", "joe"], "john") # prints False

Upvotes: 2

Related Questions