string)convert to an integer using the built-in int(functionand then use the built-in chr(function to obtain the unicode character for the given code point the function' return value (or in the case of lambda expressionthe result of the expressionis used as the replacement text the fifth re sub(call uses the regex &([ -za- ]+)to capture named entities the standard library' html entities module contains dictionaries of entitiesincluding name codepoint whose keys are entity names and whose values are integer code points the re sub(function calls the local char_from_entity(function every time it has match the char_from_entity(function uses dict get(with default argument of xfffd (the code point of the standard unicode replacement character--often depicted as this ensures that code point is always retrieved and it is used with the chr(function to return suitable character to replace the named entity with--using the unicode replacement character if the entity name is invalid the sixth re sub(call' regex\ (?:\xa \ ]+\ )+is used to delete lines that contain only whitespace the character class we have used contains spacea nonbreaking space (which &nbspentities are replaced with in the preceding regex)and tab the regex matches newline (the one at the end of line that precedes one or more whitespace-only lines)then at least one (and as many as possiblelines that contain only whitespace since the match includes the newlinefrom the line preceding the whitespace-only lines we must replace the match with single newlineotherwisewe would delete not just the whitespace-only lines but also the newline of the line that preceded them the result of the seventh and last re sub(call is returned to the caller this regex\ \ +is used to replace sequences of two or more newlines with exactly two newlinesthat isto ensure that each paragraph is separated by just one blank line in the html example none of the replacements were directly taken from the match (although html entity names and numbers were used)but in some situations the replacement might need to include all or some of the matching text for exampleif we have list of nameseach of the form forename middlename middlenamen surnamewhere there may be any number of middle names (including none)and we want to produce new version of the list with each item of the form surnameforename middlename middlenamenwe can easily do so using regexnew_names [for name in namesname re sub( "(\ +(?:\ +\ +)*)\ +(\ +)" "\ \ "namenew_names append(namethe first part of the regex(\ +(?:\ +\ +)*)matches the forename with the first \wexpression and zero or more middle names with the (?:\ +\ +)ex