Python Forum
help needed plz, how to check if a string is almost the same? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: help needed plz, how to check if a string is almost the same? (/thread-17821.html)



help needed plz, how to check if a string is almost the same? - NickPlv - Apr-25-2019

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!


RE: help needed plz - Gribouillis - Apr-25-2019

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()



RE: help needed plz - perfringo - Apr-25-2019

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!')