1

I'm a little confused regarding a Python exercise that requires a case insensitive input.

This part of the excercise that confuses me:

Make sure your comparison is case insensitive. If 'John' has been used, 'JOHN' should not be accepted.

Here is my code:

current_users = ['username_1', 'username_2', 'username_3', 'username_4',
                 'username_5']
new_user = ['new_user_1', 'new_user_2', 'new_user_3', 'username_1', 'Username_2']

for username in new_user:
    if username in current_users:
        print("Please enter a new username.")
    elif username not in current_users:
        print("This username is available.")

My problem is that I'm trying to get my code to reject "Username_2" because of the capital "U" but I have no idea how to do this. I'm reading through Python Crash Course by Eric Matthes and am currently on chapter 5 but I don't recall being taught how to reject case insensitive inputs yet.

I know of the upper(), lower(), and title() string methods and I tried using:

username.lower() == username.upper()

new_user.lower() == new_user.upper()

before my for loop, but this just results in a syntax error.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Btw, you can replace `elif username not in current_users:` with just `else:` because it always fails if `username in current_users` returns true. – Ozgur Vatansever Aug 31 '16 at 01:40
  • Seems like you would need case _sensitive_ comparisons in order for 'John' to not be considered the same as 'JOHN' — and Python string equality testing, `==`, and `in` operator _are_ both case sensitive by default. Could it be a trick question? – martineau Aug 31 '16 at 02:05

1 Answers1

5

You can convert each new username to lower case and compare it to a lower case version of the user list (created using a list comprehension).

lower_case_users = [user.lower() for user in current_users]
if new_user.lower() in lower_case_users:
    # Name clash

You may want to store your usernames in lowercase when they are first created to avoid creating a lower case version from the user list.

Alexander
  • 105,104
  • 32
  • 201
  • 196