0

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(....)
daniel
  • 13
  • 1
  • Does this answer your question? [How to replace multiple substrings of a string?](https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string) – Pranav Hosangadi Aug 23 '22 at 16:38

2 Answers2

1

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

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)
The fourth bird
  • 154,723
  • 16
  • 55
  • 70