Michal Wallace (sabren) sabren at
Sat Feb 26 19:32:59 CET 2000

Hey all,

  I posted a couple days ago about actually needing a whitespace-eating
nanovirus.. And ever since I built it, I've been using it almost every
day for text processing... Being able to indent triple-quoted-string
is a really really nice feature:

def test():

    output = textmuncher(trim("""
    this is

    goal = trim("""
    this is
        some expected
    output  text

    assert goal == output, "test failed"

Anyway, I was wondering if anyone else ever has need of that particular
capability. I think it's useful enough to go into the string module, and
I was just debating whether or not to submit it...  here's the code:

def trim(s):
    """strips leading indentation from a multi-line string."""
    lines = string.split(s, "\n")

    # strip leading blank line
    if lines[0] == "":
        lines = lines[1:]

    # strip indentation
    indent = len(lines[0]) - len(string.lstrip(lines[0]))
    for i in range(len(lines)):
        lines[i] = lines[i][indent:]

    return string.join(lines, "\n")

.. I guess it probably ought to run expandtabs(), too, but.. well..
what do you think?


- Michal

More information about the Python-list mailing list