Can Python Remove Global Indentation from Multiline Strings?

DDD
Release: 2024-10-24 12:15:29
Original
939 people have browsed it

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>
Copy after login

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

<code class="python">import textwrap

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

This will produce the following output with the indentation removed:

Controller = require 'controller'

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

    constructor: ->
        Controller.mix @
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!