import re s = '<p id="1">'print(re.sub(r'(<p)\s+(id="\d+">)', r'\1 class="test" \2', s))
Standard input is empty
<p class="test" id="1">
The brand new service which powers Ideone!
Widget for compiling and running the source code in a web browser!