Reputation: 57
I'm trying to create a function which takes a product
and checks whether that string contains a category in categories
list. The check should not be case-sensitive, but when the first match is found the function should return the value as it is given in the list. If the product does not contain any of the categories the string 'Other' should be returned.
Example:
if product = Debit card
and categories = ['Account', 'Card', 'Debit']
then assign_category(product, categories)
will return Card
.
This is the base code:
def assign_category(product, categories):
for x in range(len(categories)):
if categories[x] == product:
return product
return 'Other'
I'm struggling to find a way for the function to take account of the word, when it isn't exactly entered as so.
The list is: ['Reporting', 'Card', 'Account', 'Debt', 'Loan', 'Mortgage']
one entry in the list to break down is Debit cards
so it should return Card
any help would be greatly appreciated.
Upvotes: 0
Views: 107
Reputation: 2841
You want to compare both product and category in lowercase
categories = ['Reporting', 'Card', 'Account', 'Debt', 'Loan', 'Mortgage']
def assign_category(product, categories):
product = product.lower()
for category in categories:
if category.lower() in product:
return category
return 'Other'
>>> assign_category("Debit card", categories)
'Card'
Upvotes: 1
Reputation: 184
Use title()
for non case-sensitive check and use in
to search the category in the product. You should also return the category, not the product. The return 'Other'
statment should be outside the 'for' loop. like this:
def assign_category(product, categories):
for x in range(len(categories)):
if categories[x] in product.title():
return categories[x]
return 'Other'
I also recommend looping through categories
and not range(len(categories))
(redundent according to the question) like this:
def assign_category(product, categories):
for category in categories:
if category in product.title():
return category
return 'Other'
Upvotes: 1