import re text = "This is a sample text." pattern = "sample" matches = re.findall(pattern, text) for match in matches: text = text.replace(match, "example") print(text)