Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Case sensitive checks
#1
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.
Reply
#2
One possibility:
if 'UsEr1'.lower() == 'usER1'.lower():
print('useR1'.upper())

Paul
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Context-sensitive delimiter ZZTurn 9 1,444 May-16-2023, 07:31 AM
Last Post: Gribouillis
  Switch case or match case? Frankduc 9 4,484 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  How do I copy files without case sensitive? mcesmcsc 8 4,920 Dec-18-2019, 02:19 PM
Last Post: mcesmcsc
  Case sensitive path asheru93 6 5,943 Jan-28-2019, 01:52 PM
Last Post: asheru93
  case-sensitive search saisankalpj 1 2,202 Jul-03-2018, 02:46 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

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