Python Forum
help needed plz, how to check if a string is almost the same?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help needed plz, how to check if a string is almost the same?
#1
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!
Reply
#2
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()
Reply
#3
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!')
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I check if the first X characters of a string are numbers? FirstBornAlbratross 6 1,521 Apr-12-2023, 10:39 AM
Last Post: jefsummers
  how to check if string contains ALL words from the list? zarize 6 7,198 Jul-22-2020, 07:04 PM
Last Post: zarize
  How to check if user entered string or integer or float?? prateek3 5 11,328 Dec-21-2019, 06:24 PM
Last Post: DreamingInsanity
  How to check if value of a list is in a string? HiImNew 2 3,965 Dec-07-2017, 10:07 PM
Last Post: Larz60+
  Ho to check if string contains substring from list Rius2 2 76,644 Sep-30-2017, 07:32 PM
Last Post: Rius2
  Check to see if a string exactly matches an element in a list DBS 1 22,285 Nov-02-2016, 10:16 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020