Home  >  Article  >  Backend Development  >  Can Python Remove Global Indentation from Multiline Strings?

Can Python Remove Global Indentation from Multiline Strings?

DDD
DDDOriginal
2024-10-24 12:15:29930browse

Can Python Remove Global Indentation from Multiline Strings?

Removing Global Indentation from Multiline Strings in Python

In Python, you may encounter multiline strings with global left indentation that needs to be removed. This can occur when strings are declared within functions or other code blocks that introduce additional indentation.

Question:

Does Python provide a built-in function that can remove the global indentation of a multiline string?

Answer:

While there is no built-in function for this specific task, the Python standard library offers a solution through the textwrap.dedent() function.

textwrap.dedent() takes a multiline string as input and removes the common indentation of all its lines. This allows you to remove any unwanted global indentation.

Example:

Consider the following string with global 4-space indentation:

<code class="python">s = """
    Controller = require 'controller'

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

        constructor: ->
            Controller.mix @
"""</code>

Using textwrap.dedent(), you can remove the global indentation as follows:

<code class="python">import textwrap

result = textwrap.dedent(s)</code>

This will produce the following output with the indentation removed:

Controller = require 'controller'

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

    constructor: ->
        Controller.mix @

The above is the detailed content of Can Python Remove Global Indentation from Multiline Strings?. 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