def strip_lines(s, side='r'):
    """
    Splits the given string into lines (at newlines), strips each line
    and rejoins. Is careful about last newline and default to stripping
    on the right only (side='r'). Use 'l' for left strip or anything
    else to strip both sides.
    """
    strip = (str.rstrip if side == 'r' else str.lstrip if side == 'l'
             else str.strip)
    end = '\n' if s.endswith('\n') else ''
    return '\n'.join([strip(line) for line in s.splitlines()]) + end