Changing the Indentation of a Multiline String
Credit: Tom Good
Problem
You have a string made up of multiple lines, and you need to build another string from it, adding or removing leading spaces on each line so that the indentation of each line is some absolute number of spaces.
Solution
We
don’t need re for this. The
string module (or string methods, in Python 2.0
and later) is quite sufficient:
import string
def reindent(s, numSpaces):
s = string.split(s, '\n')
s = [(numSpaces * ' ') + string.lstrip(line) for line in s]
s = string.join(s, '\n')
return sDiscussion
When working with text, it may be necessary to change the indentation level of a block. This recipe’s code takes a multiline string and adds or removes leading spaces on each line so that the indentation level of each line of the block matches some absolute number of spaces. For example:
>>> 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
Even if the lines in s are initially indented differently, this recipe makes their indentation homogeneous. This is sometimes what we want, and sometimes not. A frequent need is to adjust the amount of leading spaces in each line, so that the relative indentation of each line in the block is preserved. This is not hard either, for either positive or negative values of the adjustment. However, negative values need a check to ensure that no nonspaces are snipped from the start ...