def strip_newlines(s, nleading=0, ntrailing=0):
    """strip at most nleading and ntrailing newlines from s"""
    for _ in range(nleading):
        if s.lstrip(' \t')[0] == '\n':
            s = s.lstrip(' \t')[1:]
        elif s.lstrip(' \t')[0] == '\r\n':
            s = s.lstrip(' \t')[2:]

    for _ in range(ntrailing):
        if s.rstrip(' \t')[-2:] == '\r\n':
            s = s.rstrip(' \t')[:-2]
        elif s.rstrip(' \t')[-1:] == '\n':
            s = s.rstrip(' \t')[:-1]

    return s