Reputation: 409
I have this code here
input1 = input("Toppings: ")
split = input1.split("|")
length = len(split)
for i in range(0, length-1):
if "cheese" in str(split[i]):
del split[i]
s = "|"
print(s.join(split))
and it's meant to take a string, split it by "|"
into an array, then search the array for the string "cheese"
, and if it finds it; take it out of the array, and then print out the parsed array.
When inputting this:
Toppings: ham|lettuce|cheddar cheese|sliced cucumber|tomato
ham|lettuce|sliced cucumber|tomato
The output is correct - it removes the element that has "cheese"
in it from the array. However, when inputting this:
Toppings: egg|lettuce|cheese spread|mac'n'cheese
egg|lettuce|mac'n'cheese
It doesn't remove it from the array. When I looked up the in
operator it said it didn't match whole word only so I thought it would work. What would be the correct code to put into the if
statement so it would detect "cheese"
in "mac'n'cheese"
?
Upvotes: 1
Views: 83
Reputation: 12022
You're modifying the list while iterating over it. Specifically, because you're removing items, but not adjusting the index, you're skipping over things; in this case, mac'n'cheese
.
You also have another problem you're happening to not run into with those inputs. Since each sample input is only having one element removed, range(0, length-1)
happens to not give an IndexError
; but if more than one element was being removed, it would.
Here's a much better way to do what you're trying to do:
toppings = input("Toppings: ").split('|')
toppings_without_cheese = (top for top in toppings if 'cheese' not in top)
print('|'.join(toppings_without_cheese))
Upvotes: 4
Reputation: 1605
I like to use a separate array and ADD allowed values to that instead of removing the disallowed ones. See "allowedToppings" and how I switched the If statement below.
input1 = input("Toppings: ")
split = input1.split("|")
length = len(split)
allowedToppings = []
for i in range(0, length-1):
if not "cheese" in str(split[i]):
allowedToppings.append(str(split[i]))
s = "|"
print(s.join(split))
Upvotes: 1
Reputation: 10595
The problem is this line:
for i in range(0, length-1):
The end of the range is already exclusive. You can do:
for i in range(0, length):
But this will throw an exception, as the pointer will pass the end of the array. The simple way to fix it is to do:
i = 0
while i<len(split):
if "cheese" in str(split[i]):
del split[i]
else:
i += 1
Upvotes: -1