Python Forum

Full Version: help needed plz, how to check if a string is almost the same?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am trying to create a program for username login etc.
My question is this: How can i tell python that it is ok if the user does not answer Exactly as i program it?
i.e. 1) If in the following code the user answer JACK, it will return "Try gain" (but JACK is also correct)
2) If answers jack Daniel (which is also correct because he answered with name and surname)will also return "Try again"
My simplified code:

username=input("login: ")
user1=("jack")
user2=("Jill")
if username == user1 :
    print("Welcome Jack!")
elif username == user2 :
    print("Welcome Jill!")
else :
    print("Try again")
any suggestions for solving those 2 problems?? thank you in advance!
You can write a function to normalize the user input, then write
norm_username = normalize(username)
if norm_username == 'jack':
    ...
For example the following function normalizes the user name to the first word of the input in lowercase characters
def normalize(username):
    return username.split()[0].lower()
One way of achieving desired result (with Python >=3.6):

- normalize input as Gribouillis suggested
- check whether username in list of users
- print capitalized username with Hello or Try Again

>>> username = input('login: ').split()[0].lower()
>>> users = ['jack', 'jill']
>>> if username in users:
...     print(f'Hello {username.capitalize()}')
... else:
...     print('Try again!')