Home > Mobile >  Python Best Way to Delete matches?
Python Best Way to Delete matches?

Time:08-24

I want to delete multiple strings from a phrase in python. For example I want to delete: apple, orange, tomato

How can I do that easily without writing 10 replaces like this:

str = str.replace('apple','').replace(....).replace(....)

CodePudding user response:

Any time you are repeating yourself, think of a loop instead.

for word in ('apple','cherry','tomato','grape'):
    str = str.replace(word,'')

And, by the way, str is a poor name for a variable, since it's the name of a type.

CodePudding user response:

You could also use re.sub and list the words in a group between word boundaries \b

import re

s = re.sub(r"\b(?:apple|orange|tomato)\b", "", s)
  • Related