11.9. Regexp Substitute

11.9.1. About

  • re.sub()

  • Replace matched substring with text

11.9.2. Example

Listing 417. Usage of re.sub()
import re


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

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