Reputation:
I'm writing a searching method and the search is case insensitive. I might be searching through lists/dicts with various data types, how do I query that if any strings exist in the list, perform an operation like string.lower() on it? Or, I don't know if this would be more time efficient, search for all instances of strings in a list, and add them case insensitive to a new set, and then search that set for the instance of my string.
Tried the any() implementation but I think I'm doing it wrong, but also not sure that it's the most effective way to do what I'm describing.
if isinstance(needle, str): #If needle is a string, convert it to lowercase and if haystack has any strings in it, convert them to lowercase too.
needle = needle.lower()
if any(str in haystack):
for item in haystack:
if type(item) == str in haystack:
item = item.lower()
Above code returns a
TypeError: 'in <string>' requires string as left operand, not type.
Which I don't really understand, as I was hoping for it to determine that there's at least one instance of a string in the haystack, then to perform the lower() function on it.
Upvotes: 2
Views: 271
Reputation: 17322
you can try:
my_list = [1, 2, 3, '1', 'A']
my_list = [e.lower() if isinstance(e, str) else e for e in my_list ]
instead of lower method, you can apply any function that works with strings
Upvotes: 0