text.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """Text related utils."""
  2. import os
  3. import re
  4. def indent(instr, nspaces=4, ntabs=0, flatten=False):
  5. """Indent a string a given number of spaces or tabstops.
  6. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
  7. Parameters
  8. ----------
  9. instr : basestring
  10. The string to be indented.
  11. nspaces : int (default: 4)
  12. The number of spaces to be indented.
  13. ntabs : int (default: 0)
  14. The number of tabs to be indented.
  15. flatten : bool (default: False)
  16. Whether to scrub existing indentation. If True, all lines will be
  17. aligned to the same indentation. If False, existing indentation will
  18. be strictly increased.
  19. Returns
  20. -------
  21. str|unicode : string indented by ntabs and nspaces.
  22. """
  23. if instr is None:
  24. return None
  25. ind = "\t" * ntabs + " " * nspaces
  26. pat = re.compile("^\\s*", re.MULTILINE) if flatten else re.compile("^", re.MULTILINE)
  27. outstr = re.sub(pat, ind, instr)
  28. if outstr.endswith(os.linesep + ind):
  29. return outstr[: -len(ind)]
  30. return outstr