I'm trying to find a way to remove specific words from a list and have the possibility to remove everything from that list after the word has an attached special character after it.
How I currently remove just the specific items:
import re
fruits = "Banana Apple Strawberry Cherry Pear Melon Orange"
remove_fruits = "Cherry", "Orange"
fruits_list = fruits.split()
clean_items = []
re_remove_fruits = [fruit for fruit in remove_fruits if "\\" in fruit]
non_re_remove_fruits = [fruit for fruit in remove_fruits if fruit not in re_remove_fruits]
for fruit in fruits_list:
for remove_fruit in re_remove_fruits:
fruit = re.sub(remove_fruit, "", fruit)
for remove_fruit in non_re_remove_fruits:
if fruit.upper() == remove_fruit.upper():
fruit = ""
if fruit:
clean_items.append(fruit)
cleaned_list = " ".join(clean_items)
print (cleaned_list)
Banana Apple Strawberry Pear Melon
How I would like to have them removed:
fruits = "Banana Apple Strawberry Cherry Pear Melon Orange"
remove_fruits = "Apple", "Orange", "Pear#"
result = "Banana Strawberry Cherry"
CodePudding user response:
Here is a simple for-loop to do it:
fruits = "Banana Apple Strawberry Cherry Pear Melon Orange"
remove_fruits = { "Apple", "Orange", "Pear#" }
good_fruits = []
for fruit in fruits.split(' '):
if fruit in remove_fruits:
continue
if fruit '#' in remove_fruits:
break
good_fruits.append(fruit)
result = " ".join(good_fruits)
print(result)
Output:
Banana Strawberry Cherry
CodePudding user response:
here is something you need:
fruits = "Banana Apple Strawberry Cherry Pear Melon Orange"
remove_fruits = "Apple", "Orange", "Pear#"
fruits_list = fruits.split()
special_char = "#"
new_list = []
for each in fruits_list:
if each special_char in remove_fruits:
break
else:
if each not in remove_fruits:
new_list.append(each)
" ".join(new_list)
Output:
Banana Strawberry Cherry
