Search code examples
pythonstringindentation

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


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 @"

Solution

  • 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 @