From 495d5c2e969990b90787c1d3c4dea25856ec7004 Mon Sep 17 00:00:00 2001 From: Mahmoud Hashemi Date: Sun, 24 Jan 2016 00:47:01 -0800 Subject: [PATCH] adding strutils.indent --- boltons/strutils.py | 18 +++++++++++++++++- tests/test_strutils.py | 10 ++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/boltons/strutils.py b/boltons/strutils.py index cff79c4..d2980af 100644 --- a/boltons/strutils.py +++ b/boltons/strutils.py @@ -27,7 +27,7 @@ except NameError: # basestring not defined in Python 3 __all__ = ['camel2under', 'under2camel', 'slugify', 'split_punct_ws', 'unit_len', 'ordinalize', 'cardinalize', 'pluralize', 'singularize', 'asciify', 'html2text', 'strip_ansi', 'bytes2human', 'find_hashtags', - 'a10n', 'gunzip_bytes', 'iter_splitlines'] # 'StringBuffer'] + 'a10n', 'gunzip_bytes', 'iter_splitlines', 'indent'] # 'StringBuffer'] _punct_ws_str = string.punctuation + string.whitespace @@ -627,3 +627,19 @@ def iter_splitlines(text): if tail: yield tail return + + +def indent(text, margin, newline='\n', key=bool): + """The missing counterpart to the built-in :func:`textwrap.dedent`. + + Args: + text (str): The text to indent. + margin (str): The string to prepend to each line. + newline (str): The newline used to rejoin the lines (default: \\n) + key (callable): Called on each line to determine whether to + indent it. Default: :class:`bool`, to ensure that empty lines do + not get whitespace added. + """ + indented_lines = [(margin + line if key(line) else line) + for line in iter_splitlines(text)] + return newline.join(indented_lines) diff --git a/tests/test_strutils.py b/tests/test_strutils.py index cfd21a0..bdc9993 100644 --- a/tests/test_strutils.py +++ b/tests/test_strutils.py @@ -1,10 +1,16 @@ # -*- coding: utf-8 -*- -from boltons.strutils import asciify +from boltons import strutils def test_asciify(): ref = u'Beyoncé' - b = asciify(ref) + b = strutils.asciify(ref) assert len(b) == len(b) assert b[-1:].decode('ascii') == 'e' + + +def test_indent(): + to_indent = '\nabc\ndef\n\nxyz\n' + ref = '\n abc\n def\n\n xyz\n' + assert strutils.indent(to_indent, ' ') == ref