summaryrefslogtreecommitdiffstats
path: root/Lib/textwrap.py
diff options
context:
space:
mode:
authorNick Coghlan <ncoghlan@gmail.com>2012-06-11 13:07:51 (GMT)
committerNick Coghlan <ncoghlan@gmail.com>2012-06-11 13:07:51 (GMT)
commit4fae8cdaeac117c6a567f9305a22fd0cff400452 (patch)
treef01b63d1495c581d36e0f346cb8fa23a8b160045 /Lib/textwrap.py
parent3c4acd8bf9b7f2e1dcfd5bb76c4562451c3d8fa1 (diff)
downloadcpython-4fae8cdaeac117c6a567f9305a22fd0cff400452.zip
cpython-4fae8cdaeac117c6a567f9305a22fd0cff400452.tar.gz
cpython-4fae8cdaeac117c6a567f9305a22fd0cff400452.tar.bz2
Close #13857: Added textwrap.indent() function (initial patch by Ezra
Berch)
Diffstat (limited to 'Lib/textwrap.py')
-rw-r--r--Lib/textwrap.py21
1 files changed, 20 insertions, 1 deletions
diff --git a/Lib/textwrap.py b/Lib/textwrap.py
index 66ccf2b..7024d4d 100644
--- a/Lib/textwrap.py
+++ b/Lib/textwrap.py
@@ -7,7 +7,7 @@
import re
-__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent']
+__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent']
# Hardcode the recognized whitespace characters to the US-ASCII
# whitespace characters. The main reason for doing this is that in
@@ -386,6 +386,25 @@ def dedent(text):
text = re.sub(r'(?m)^' + margin, '', text)
return text
+
+def indent(text, prefix, predicate=None):
+ """Adds 'prefix' to the beginning of selected lines in 'text'.
+
+ If 'predicate' is provided, 'prefix' will only be added to the lines
+ where 'predicate(line)' is True. If 'predicate' is not provided,
+ it will default to adding 'prefix' to all non-empty lines that do not
+ consist solely of whitespace characters.
+ """
+ if predicate is None:
+ def predicate(line):
+ return line.strip()
+
+ def prefixed_lines():
+ for line in text.splitlines(True):
+ yield (prefix + line if predicate(line) else line)
+ return ''.join(prefixed_lines())
+
+
if __name__ == "__main__":
#print dedent("\tfoo\n\tbar")
#print dedent(" \thello there\n \t how are you?")