From af7a77313cc1585fa0e19f862df0d8c979455623 Mon Sep 17 00:00:00 2001 From: Valentin Lab Date: Wed, 4 Feb 2015 18:32:00 +0700 Subject: [PATCH] new: added a ``dedent()`` function. --- README.rst | 18 ++++++++++++++++++ src/kids/txt/__init__.py | 3 +-- src/kids/txt/txt.py | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 0b6c26d..e60868a 100644 --- a/README.rst +++ b/README.rst @@ -78,6 +78,24 @@ You can easily indent text with:: | +dedent +------ + +You can also dedent text:: + + >>> print(txt.dedent( + ... '''This is a doc + ... + ... with fancy indentation, that should just work also. + ... Without removing too much neither as: + ... - more space.''')) + This is a doc + + with fancy indentation, that should just work also. + Without removing too much neither as: + - more space. + + paragrap_wrap ------------- diff --git a/src/kids/txt/__init__.py b/src/kids/txt/__init__.py index 7ade66a..4ca40f9 100644 --- a/src/kids/txt/__init__.py +++ b/src/kids/txt/__init__.py @@ -1,4 +1,3 @@ # Package placeholder -from .txt import indent, paragraph_wrap - +from .txt import indent, dedent, paragraph_wrap diff --git a/src/kids/txt/txt.py b/src/kids/txt/txt.py index ec04ea5..89d26b1 100644 --- a/src/kids/txt/txt.py +++ b/src/kids/txt/txt.py @@ -7,6 +7,40 @@ import re +def dedent(txt): + """Dedent a txt, tolerating first line not indented. + + >>> from __future__ import print_function + + Various issues should be tackled: + + >>> print(dedent( + ... '''This is a doc + ... + ... with fancy indentation, that should just work also. + ... Without removing too much neither as: + ... - more space.''')) + This is a doc + + with fancy indentation, that should just work also. + Without removing too much neither as: + - more space. + + Note that the first line doesn't have indentation and neither the + second (which is empty). + + Of course, ``dedent`` should not fail on empty string neither: + + >>> dedent("") + '' + + """ + if "\n" not in txt: + return txt.lstrip() + first_line, end = txt.split('\n', 1) + return "%s\n%s" % (first_line, textwrap.dedent(end)) + + ## Note that a quite equivalent function was added to textwrap in python 3.3 def indent(text, prefix=" ", first=None): """Return text string indented with the given prefix