Python Forum

Full Version: Case sensitive checks
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a list of current users in list.
I have a list of new users in a list.

I want to loop through the new users and make sure the username has not been used already. If it has print a bespoke message.

This works fine as below:

current_users = ['user1', 'user2', 'user3', 'user4', 'user5']

new_users = ['user1', 'user11', 'user12', 'user13']

for user in new_users:
    if user in current_users:
        print("Username already used")
    else:
        print("OK go ahead")
BUT the problem is that usernames can be in any case.

Is there a way straightforward way in Python I can check equality regardless of the case?

Thanks in advance.
One possibility:
if 'UsEr1'.lower() == 'usER1'.lower():
print('useR1'.upper())

Paul
If you care about unicode, you might want to consider normalization as well. Some non-ascii characters can be created by multiple codepoints. Normalization would map them all to a single codepoint that could be compared.

If you're not doing that, you could at least do casefold() which will handle some non-ascii oddities. If you're completely ascii, casefold() should do the same thing as lower().

I would store all the casefolded/lowered versions in a set and use that for comparison. Then store the unfolded version for display.

existing_users = ["Jane", "Hosokai", "Ganesh", "Søren", "Günter", "René"]
new_users = ["Sarah", "ganesh", "Rene", "jane", "sarah"]

folded_names = {x.casefold() for x in existing_users}

for name in new_users:
    if name.casefold() in folded_names:
        print(f"The username {name} collides with an existing user.")
    else:
        folded_names.add(name.casefold())
        existing_users.append(name)
        print(f"Added {name} to the list of users")

print(f"The user list is now:")
print(",".join(existing_users))
Output:
Added Sarah to the list of users The username ganesh collides with an existing user. Added Rene to the list of users The username jane collides with an existing user. The username sarah collides with an existing user. The user list is now: Jane,Hosokai,Ganesh,Søren,Günter,René,Sarah,Rene