5.9. Regexp Substitute

5.9.1. About

  • re.sub()

  • Replace matched substring with text

5.9.2. Examples

Listing 5.73. 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'