Home  >  Article  >  Backend Development  >  How to Remove Global Indentation from Multiline Strings in Python?

How to Remove Global Indentation from Multiline Strings in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 01:16:02916browse

How to Remove Global Indentation from Multiline Strings in Python?

Removing Global Indentation from Multiline Strings in Python

If you have a multiline string with global indentation, you may need to remove it to conform to a certain style or functionality. While Python doesn't offer a built-in function specifically for this purpose, the standard library provides textwrap.dedent() to address this need.

To use dedent(), simply pass your indented multiline string as an argument to the function. It will automatically detect and remove the global indentation from the string. For example, consider the following indented string:

s = """
    Controller = require 'controller'

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

        constructor: ->
            Controller.mix @
"""

Calling dedent(s) on this string would produce the following output:

Controller = require 'controller'

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

    constructor: ->
        Controller.mix @

As you can see, the global indentation has been removed from each line of the string, giving you a clean and properly indented multiline string.

The above is the detailed content of How to Remove Global Indentation from Multiline Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn