diff options
author | Greg Ward <gward@python.net> | 2003-05-08 01:58:05 (GMT) |
---|---|---|
committer | Greg Ward <gward@python.net> | 2003-05-08 01:58:05 (GMT) |
commit | 478cd48dee2e40fe009d07c73360c9abbed2ffe4 (patch) | |
tree | 9e4b5da2edf65b5921afdb4a91e7eb079430a702 /Lib/textwrap.py | |
parent | 4656ed44ca0cf90225ea1da04fa4154c77f02b0e (diff) | |
download | cpython-478cd48dee2e40fe009d07c73360c9abbed2ffe4.zip cpython-478cd48dee2e40fe009d07c73360c9abbed2ffe4.tar.gz cpython-478cd48dee2e40fe009d07c73360c9abbed2ffe4.tar.bz2 |
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.
Diffstat (limited to 'Lib/textwrap.py')
-rw-r--r-- | Lib/textwrap.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/Lib/textwrap.py b/Lib/textwrap.py index b0c7042..ec0e7cb 100644 --- a/Lib/textwrap.py +++ b/Lib/textwrap.py @@ -306,3 +306,45 @@ def fill(text, width=70, **kwargs): """ 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) |