You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
"""Text related utils."""
|
|
|
|
import os
|
|
import re
|
|
|
|
|
|
def indent(instr, nspaces=4, ntabs=0, flatten=False):
|
|
"""Indent a string a given number of spaces or tabstops.
|
|
|
|
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
|
|
|
|
Parameters
|
|
----------
|
|
|
|
instr : basestring
|
|
The string to be indented.
|
|
nspaces : int (default: 4)
|
|
The number of spaces to be indented.
|
|
ntabs : int (default: 0)
|
|
The number of tabs to be indented.
|
|
flatten : bool (default: False)
|
|
Whether to scrub existing indentation. If True, all lines will be
|
|
aligned to the same indentation. If False, existing indentation will
|
|
be strictly increased.
|
|
|
|
Returns
|
|
-------
|
|
|
|
str|unicode : string indented by ntabs and nspaces.
|
|
|
|
"""
|
|
if instr is None:
|
|
return None
|
|
ind = "\t" * ntabs + " " * nspaces
|
|
pat = re.compile("^\\s*", re.MULTILINE) if flatten else re.compile("^", re.MULTILINE)
|
|
outstr = re.sub(pat, ind, instr)
|
|
if outstr.endswith(os.linesep + ind):
|
|
return outstr[: -len(ind)]
|
|
return outstr
|