Does Python have a built-in function for unindenting a multiline string?

Hubro picture Hubro · Jun 22, 2012 · Viewed 14.2k times · Source

Say I have the string

s = """
    Controller = require 'controller'

    class foo
        view: 'baz'
        class: 'bar'

        constructor: ->
            Controller.mix @
"""

Every line in the string now has a global 4 space indentation. If this string was declared inside a function, it would have a 8 space global indentation, etc.

Does Python have a function for removing the global left indentation of string?

I would like that function output to be:

Controller = require 'controller'

class foo
    view: 'baz'
    class: 'bar'

    constructor: ->
        Controller.mix @"

Answer

Sven Marnach picture Sven Marnach · Jun 22, 2012

Not a built-in function, but a function in the standard library: textwrap.dedent()

>>> print(textwrap.dedent(s))

Controller = require 'controller'

class foo
    view: 'baz'
    class: 'bar'

    constructor: ->
        Controller.mix @