The problem is not only the letter "E", but the fact that the code fails when the list current_users
has names that mix uppercase and lowercase letters. After all, only in the new_user
that you turn everything into uppercase or lowercase (in your case, you’re comparing ze
, Ze
and ZE
with zE
, and then it won’t even work).
If you want to make comparisons case insensitive, can use the method casefold()
. This method is similar to lower()
, but according to the documentation, he is more "aggressive" and treats special cases, as for example the character ß
, which, when converted to capital, becomes "SS" (then 'ß'.upper().lower()
returns "ss"):
print('ß'.lower() == 'SS'.lower()) # False
print('ß'.casefold() == 'SS'.casefold()) # True
Of course for letters of a
to z
not accentuated, will not make so much difference use lower()
or casefold()
, but finally.
So just apply casefold()
in the list of current users, and also in each user you are checking:
current_users = ['ZE', 'carmo', 'SofiA', 'jeff', 'isa']
new_users = ['ze', 'didao', 'edi', 'taria', 'sofia']
current_users_fold = list(map(lambda user: user.casefold(), current_users))
for new_user in new_users:
if new_user.casefold() not in current_users_fold:
print('O nome "' + new_user.title() + '" está disponível.')
else:
print('Forneça outro nome.')
First I use map
to create another list containing the version casefolded of current users. Then I apply the casefold()
for every new user I’m checking.
The exit is:
Forneça outro nome.
O nome "Didao" está disponível.
O nome "Edi" está disponível.
O nome "Taria" está disponível.
Forneça outro nome.
Another alternative is to use set
to find the intersection between the two lists (i.e., existing users), and use this list to check for non-existent ones:
def ajusta(s):
return s.casefold()
existentes = list( set(map(ajusta, current_users)) & set(map(ajusta, new_users)) )
nao_existentes = [ new_user for new_user in new_users if new_user.casefold() not in existentes]
print(existentes) # ['sofia', 'ze']
print(nao_existentes) # ['didao', 'edi', 'taria']
Once you have both lists (existing and non-existent users), you can use them any way you want.
Thanks, I’m learning python every help is welcome. I edited the code based on yours and gave it right :)
– Dev NOOB