-1

Let's say that you wish to check existing usernames in a list using Python, ensuring that we check for case sensitivity, such that we force new users to select a unique username so you write something that looks like this:

current_users = ['lana', 'matthew', 'kevin', 'lars', 'louis', 'sarah']
new_users = ['tom', 'tim', 'gus', 'david']

for user in new_users:
    if user.title().upper().lower() in current_users:
        print("Sorry, " + user.title() + ", but that username is 
        already taken. Please choose a new username.")
else:
    print("Hello, " + user.title() + ", that username is available. 
    Welcome aboard!")

I've tested the code and I know that it works, but I don't pretend to be the world's best coder, and this code doesn't look to be the most efficient.

Is there another way to do this in Python without chaining .title().upper().lower() to check for case sensitivity?

Also, how would one test for a user who capitalised a character inside the username, such as 'maTThew'?

jpp
  • 159,742
  • 34
  • 281
  • 339
mpyeager
  • 13
  • 2

2 Answers2

2

You should use str.casefold for case insensitivity:

current_users = ['lana', 'matthew', 'kevin', 'lars', 'louis', 'sarah']
new_users = ['tom', 'tim', 'gus', 'david']

for user in new_users:
    if user.casefold() in current_users:
        print("Sorry, " + user.title() + ", but that username is already taken. Please choose a new username.")
else:
    print("Hello, " + user.title() + ", that username is available. Welcome aboard!")

As per the docs:

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

jpp
  • 159,742
  • 34
  • 281
  • 339
0

using title(), upper(), lower() combined together make no sense, Just use lower() function to test.

if user.lower() in current_users:
   some code here
Ankireddy
  • 179
  • 1
  • 6