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>
Tags: text
faster to map. Hi,
The form:
is pretty tricky (I hadn't seen it before), but it's faster (and easier for me to read it) as:
At least, it's faster on my timing tests.
with map. Thanks for the comment. Interesting... Using map I guess it would be something like:
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
I found that teh recipe doesnt keep newlines so my modified function is like this:
</pre>
Here's a 1-liner:
where
s
is the original string andnumSpaces
is the number of spaces to prepend to each line