7.9. Regexp Substitute

7.9.1. About

  • re.sub()

  • Replace matched substring with text

7.9.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'