# credit to the Stack Overflow user in the source link re.sub('(s+)(a|an|and|the)(s+)', '13', text) # leaves the residual whitespace re.sub('s+(a|an|and|the)(s+)', '2', text) # removes the whitespace