Issue
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"
Solution
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
Answered By - Muhammad Burhan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.