How to remove extra indentation of Python triple quoted multi-line strings?

Mike picture Mike · Sep 11, 2009 · Viewed 30.7k times · Source

I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A problem script would be something so simple as:

"""foo
bar
foo2"""

So when in the main method it would look like:

def main():
    """foo
    bar
    foo2"""

and the string would now have an extra tab at the beginning of every line.

Answer

thraxil picture thraxil · Sep 11, 2009

textwrap.dedent from the standard library is there to automatically undo the wacky indentation.