[Python-checkins] python/dist/src/Lib textwrap.py,1.26,1.27
gward@users.sourceforge.net
gward@users.sourceforge.net
Wed, 07 May 2003 18:58:07 -0700
Update of /cvsroot/python/python/dist/src/Lib
In directory sc8-pr-cvs1:/tmp/cvs-serv32627
Modified Files:
textwrap.py
Log Message:
SF patch #598163 (Ville Vainio, vvainio@users.sourceforge.net):
add dedent() function, to remove indentation from multiline strings
(eg. triple-quoted strings). Differs from inspect.getdoc() by not
special-casing the first line (often a sensible approach for
non-docstring multiline strings). This should make this function more
general (symmetric 'indent' also possible), and more fitting for the
textwrap module.
Index: textwrap.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/textwrap.py,v
retrieving revision 1.26
retrieving revision 1.27
diff -C2 -d -r1.26 -r1.27
*** textwrap.py 7 May 2003 01:20:58 -0000 1.26
--- textwrap.py 8 May 2003 01:58:05 -0000 1.27
***************
*** 307,308 ****
--- 307,350 ----
w = TextWrapper(width=width, **kwargs)
return w.fill(text)
+
+
+ # -- Loosely related functionality -------------------------------------
+
+ def dedent(text):
+ """dedent(text : string) -> string
+
+ Remove any whitespace than can be uniformly removed from the left
+ of every line in `text`.
+
+ This can be used e.g. to make triple-quoted strings line up with
+ the left edge of screen/whatever, while still presenting it in the
+ source code in indented form.
+
+ For example:
+
+ def test():
+ # end first line with \ to avoid the empty line!
+ s = '''\
+ Hey
+ there
+ '''
+ print repr(s) # prints ' Hey\n there\n '
+ print repr(dedent(s)) # prints 'Hey\nthere\n'
+ """
+ lines = text.expandtabs().split('\n')
+ margin = None
+ for line in lines:
+ content = len(line.lstrip())
+ if not content:
+ continue
+ indent = len(line) - content
+ if margin is None:
+ margin = indent
+ else:
+ margin = min(margin, indent)
+
+ if margin is not None:
+ for i in range(len(lines)):
+ lines[i] = lines[i][margin:]
+
+ return '\n'.join(lines)