username = 'MICHAEL89'
if username.upper() in (name.upper() for name in USERNAMES):
...
Alternatively:
if username.upper() in map(str.upper, USERNAMES):
...
Or, yes, you can make a custom method.
Answer from nmichaels on Stack Overflowusername = 'MICHAEL89'
if username.upper() in (name.upper() for name in USERNAMES):
...
Alternatively:
if username.upper() in map(str.upper, USERNAMES):
...
Or, yes, you can make a custom method.
str.casefold is recommended for case-insensitive string matching. @nmichaels's solution can trivially be adapted.
Use either:
if 'MICHAEL89'.casefold() in (name.casefold() for name in USERNAMES):
Or:
if 'MICHAEL89'.casefold() in map(str.casefold, USERNAMES):
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".
I have simple find loop but I want it to ignore case and I just cant get it to .
import re
names = ['Tilt back', 'speed', 'gist']
for name in names:
if name.startswith('tilt', re.IGNORECASE):
print(name)Hi all,
I'm learning python and have been trying to figure out how to properly compare lists for case insensitivity. If I have two lists, where the first list contains the current user names and the second list is a list of new usernames, how do I get to make sure that if a new user name John won't conflict with a username in the current users of JoHn or JOHN and vice versa?
I have this so far:
current_users = ['John', 'BiLl', 'simcitizzon', 'mIke', 'cHarlie', 'admin']
new_users = ['john', 'simcitiZzon', 'ralphwiggum', 'cherrymcsperry', 'sweettooth347']
for user in new_users:
if user in current_users:
print("Sorry, " + user + " is taken.")
else:
print(user + ", this username is available")Here is the relevant section of code as I originally wrote it:
elif choice == "4":
print('What would you like to find? ')
search_item = input()
if search_item not in thislist:
print ("Not found in this list:")
else:
print ("Found in this list:")
print(', '.join(thislist))...but it turned out that this was case-sensitive to user input, which is not desired, so I tried...
elif choice == "4":
print('What would you like to find? ')
search_item = input()
if (search_item.lower() not in thislist.lower()):
print ("Not found in this list:")
else:
print ("Found in this list:")
print(', '.join(thislist))...as mentioned, for instance here. But it doesn't work, and I get...
Traceback (most recent call last): File "main.py", line 39, in <module> if (search_item.lower() not in thislist.lower()): AttributeError: 'list' object has no attribute 'lower'
I'm guessing that maybe it's because one or both of these isn't a string, but I'm not sure how to fix that if that is really the problem. Any help please? TIA.
BTW, I'm using https://repl.it, as I don't have a Python IDE installed on my home PC.
Using lower to convert the tuple to lower case for comparison
list2= [('Tom','100'),('Alex','200')]
list3= [('tom','100'),('alex','200')]
non_match = []
for line in list2:
name, val = line
if (name.lower(), val) not in list3:
non_match.append(line)
print(non_match)
You can't avoid transforming your data to some case-insensitive format, at some point. What you can do is to avoid recreating the full lists:
def make_canonical(line):
name, number = line
return (name.lower(), number)
non_match = []
for line2 in list2:
search = make_canonical(line2)
for line3 in list3:
canonical = make_canonical(line3)
if search == canonical:
break
else:
# Did not hit the break
non_match.append(line3)
In Python 3.3+ there is the str.casefold method that's specifically designed for caseless matching:
sorted_list = sorted(unsorted_list, key=str.casefold)
In Python 2 use lower():
sorted_list = sorted(unsorted_list, key=lambda s: s.lower())
It works for both normal and unicode strings, since they both have a lower method.
In Python 2 it works for a mix of normal and unicode strings, since values of the two types can be compared with each other. Python 3 doesn't work like that, though: you can't compare a byte string and a unicode string, so in Python 3 you should do the sane thing and only sort lists of one type of string.
>>> lst = ['Aden', u'abe1']
>>> sorted(lst)
['Aden', u'abe1']
>>> sorted(lst, key=lambda s: s.lower())
[u'abe1', 'Aden']
>>> x = ['Aden', 'abel']
>>> sorted(x, key=str.lower) # Or unicode.lower if all items are unicode
['abel', 'Aden']
In Python 3 str is unicode but in Python 2 you can use this more general approach which works for both str and unicode:
>>> sorted(x, key=lambda s: s.lower())
['abel', 'Aden']
Hi everyone, I am just starting to learn how to code, running into a problem when I try to compare two lists, my code is below:
current_users = ['May', 'April', 'Wu', 'Su', 'Lulu'] new_users = ['may', 'mike', 'jones', 'chow', 'paul'] for new_user in new_users: if new_user in current_users: print('username '+new_user+' is not available.') else: print('welcome')
when I try to make the current_users list case insensitive for comparing, I used:
current_users.lower() ==['may', 'april', 'wu', 'su', 'lulu']
when I run the code, result in a violation, stated that list can not have contribute .lower().
Is there anyway to make the list case insensitive?
thanks in advance.
For this simple example you can just compare lowercased rules with "yes":
rules = input ("Would you like to read the instructions? ")
rulesa = "yes"
if rules.lower() == rulesa:
print ("No cheating")
else:
print ("Have fun!")
It is OK for many cases, but be awared, some languages may give you a tricky results. For example, German letter ร gives following:
"ร".lower() is "ร"
"ร".upper() is "SS"
"ร".upper().lower() is "ss"
("ร".upper().lower() == "ร".lower()) is False
So we may have troubles, if our string was uppercased somewhere before our call to lower().
Same behaviour may also be met in Greek language. Read the post
https://stackoverflow.com/a/29247821/2433843 for more information.
So in generic case, you may need to use str.casefold() function (since python3.3), which handles tricky cases and is recommended way for case-independent comparation:
rules.casefold() == rulesa.casefold()
instead of just
rules.lower() == rulesa.lower()
Use the following:
if rules.lower() == rulesa.lower():
This converts both strings to lower case before testing for equality.