How do I remove multiple words from a strting in python

Question:

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:"

Asked By: Matsumoto

||

Answers:

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:", "")
Answered By: WingedSeal

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)

Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.