#!/usr/bin/python3 import re txt = "This is a test! \n \n\t\n" print('Expected:', [txt.rstrip() + "\n"]) # Note that adding a ,1 substitution limit works around the issue. txt = re.sub(r'(\s*)$', "\n", txt) print('Actual :', [txt]) # Beginning in 3.7, this outputs: # Expected: ['This is a test!\n'] # Actual : ['This is a test!\n\n']