Home > Back-end >  How do I remove multiple words from a strting in python
How do I remove multiple words from a strting in python

Time:01-17

I know that how do I remove a single word. But I can't remove multiple words. Can you help me? This is my string and I want to remove "Color:", "Ring size:" and "Personalization:".

string = "Color:Silver,Ring size:6 3/4 US,Personalization:J"

I know that how do I remove a single word. But I can't remove multiple words. I want to remove "Color:", "Ring size:" and "Personalization:"

CodePudding user response:

Seems like a good job for a regex.

Specific case:

import re

out = re.sub(r'(Color|Ring size|Personalization):', '', string)

Generic case (any word before :):

import re

out = re.sub(r'[^:,] :', '', string)

Output: 'Silver,6 3/4 US,J'

Regex:

[^:,]    # any character but , or :
:        # followed by :

replace with empty string (= delete)

CodePudding user response:

string = "Color:Silver,Ring size:6 3/4 US,Personalization:J"
def remove_words(string: str, words: list[str]) -> str:
    for word in words:
        string = string.replace(word, "")
    return string

new_string = remove_words(string, ["Color:", "Ring size:", "Personalization:"])

Alternative:

string = "Color:Silver,Ring size:6 3/4 US,Personalization:J"
new_string = string.replace("Color:", "").replace("Ring size:", "").replace("Personalization:", "")
  • Related