How to Unindent a Multiline String in Python?

DDD
Release: 2024-11-01 09:27:02
Original
577 people have browsed it

How to Unindent a Multiline String in Python?

Unindenting a Multiline String in Python

In Python, working with multiline strings can sometimes introduce unwanted global indentation, making it challenging to work with the string as desired. If you have a string with global indentation and want to remove it, a built-in function might not readily come to mind.

Solution: Utilizing textwrap.dedent()

While Python does not have a dedicated built-in function for unindenting strings, the solution lies in the standard library. The 'textwrap' module provides a function called 'dedent()', specifically designed to remove common leading whitespace from a multiline string.

To use 'dedent()', simply pass the indented string as an argument, and it will automatically strip away any leading whitespace that is consistent across all lines in the string. The result is a乾淨、unindented string, allowing you to work with it as needed.

Example:

Consider the following indented string:

s = """
    Controller = require 'controller'

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

        constructor: ->
            Controller.mix @
"""
Copy after login

Using 'textwrap.dedent()', we can unindent the string:

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

Controller = require 'controller'

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

    constructor: ->
        Controller.mix @
Copy after login

As you can see, the global 4-space indentation has been removed, resulting in a string that is ready for further processing or manipulation.

The above is the detailed content of How to Unindent a Multiline String in Python?. 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!