working with python regular expressions the sub(function the sub(function replaces occurrences of the regular expression pattern in the string with the repl string re sub(patternreplstringmax= this method replaces all occurrences of the regular expression pattern in string with replsubstituting all occurrences unless max is provided this method returns the modified string import re pattern '(england|wales|scotland)input 'england for footballwales for rugby and scotland for the highland gamesprint(re sub(pattern'england'input )which generatesengland for footballengland for rugby and england for the highland games you can control the number of replacements by specifying the count parameterthe following code replaces the first occurrencesimport re pattern '(england|wales|scotland)input 'england for footballwales for rugby and scotland for the highland gamesx re sub(pattern'wales'input print(xwhich produces wales for footballwales for rugby and scotland for the highland games you can also find out how many substitutions were made using the subn(function this function returns the new string and the number of substitutions in tuple