Welcome, guest | Sign In | My Account | Store | Cart
Python, 5 lines
1
2
3
4
5
def reindent(s, numSpaces):
    s = string.split(s, '\n')
    s = [(numSpaces * ' ') + string.lstrip(line) for line in s]
    s = string.join(s, '\n')
    return s

When working with text, it may be necessary to change the indentation level of a block. This code will take a multiline string and add or remove leading spaces to each line so that the indentation level of the block matches some absolute number of spaces.

<pre>

>>> x = """line one
... line two
... and line three
... """
>>> print x
line one
line two
and line three



>>> print reindent(x, 8)
        line one
        line two
        and line three
</pre>

4 comments

p a 20 years, 4 months ago  # | flag

faster to map. Hi,

The form:

g=[blah(i) for i in foo]

is pretty tricky (I hadn't seen it before), but it's faster (and easier for me to read it) as:

g=map(blah, foo)

At least, it's faster on my timing tests.

Tom Good (author) 20 years, 4 months ago  # | flag

with map. Thanks for the comment. Interesting... Using map I guess it would be something like:

def indentLine(line, spaces=8):
    return (' ' * spaces) + string.lstrip(line)

def reindentBlock(s, numSpaces):
    s = string.split(s, '\n')
    s = map(lambda a, ns=numSpaces: indentLine(a, ns), s)
    s = string.join(s, '\n')
    return s

When I tested this particular example, I found that it ran slightly slower than the version that uses a list comprehension, but they were very close.

Tom Good

Toni Brkic 15 years, 6 months ago  # | flag

I found that teh recipe doesnt keep newlines so my modified function is like this:

            leadingSpace = self.indents * '    '
            lines = outstr.splitlines(True)
            for i in range(len(lines)):
                if lines[i].strip(): # Keep empty lines
                    lines[i] = leadingSpace+lines[i].lstrip()

I found that teh recipe doesnt keep newlines so my modified
function is like this:

<pre>
            leadingSpace = self.indents * '    '
            lines = outstr.splitlines(True)
            for i in range(len(lines)):
                if lines[i].strip(): # Keep empty lines
                    lines[i] = leadingSpace+lines[i].lstrip()

</pre>

Jake Hartz 10 years ago  # | flag

Here's a 1-liner:

str = "\n".join((numSpaces * " ") + i for i in s.splitlines())

where s is the original string and numSpaces is the number of spaces to prepend to each line