How to remove extra indentation of Python triple quoted multi-line strings?
From what I see, a better answer here might be inspect.cleandoc
, which does much of what textwrap.dedent
does but also fixes the problems that textwrap.dedent
has with the leading line.
The below example shows the differences:
>>> import textwrap>>> import inspect>>> x = """foo bar baz foobar foobaz """>>> inspect.cleandoc(x)'foo bar\nbaz\nfoobar\nfoobaz'>>> textwrap.dedent(x)'foo bar\n baz\n foobar\n foobaz\n'>>> y = """... foo... bar... """>>> inspect.cleandoc(y)'foo\nbar'>>> textwrap.dedent(y)'\nfoo\nbar\n'>>> z = """\tfoobar\tbaz""">>> inspect.cleandoc(z)'foo\nbar baz'>>> textwrap.dedent(z)'\tfoo\nbar\tbaz\n'
Note that inspect.cleandoc
also expands internal tabs to spaces.This may be inappropriate for one's use case, but works fine for me.
What follows the first line of a multiline string is part of the string, and not treated as indentation by the parser. You may freely write:
def main(): """foobarfoo2""" pass
and it will do the right thing.
On the other hand, that's not readable, and Python knows it. So if a docstring contains whitespace in it's second line, that amount of whitespace is stripped off when you use help()
to view the docstring. Thus, help(main)
and the below help(main2)
produce the same help info.
def main2(): """foo bar foo2""" pass