9.18. RE Substitute

9.18.1. Rationale

  • re.sub()

  • Replace matched substring with text

9.18.2. Examples

Usage of re.sub():

import re


PATTERN = r'\s[a-z]{3}\s'
DATA = 'Baked Beans And Spam'

re.sub(PATTERN, ' & ', DATA, flags=re.IGNORECASE)
# 'Baked Beans & Spam'