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 @ """
Using 'textwrap.dedent()', we can unindent the string:
>>> print(textwrap.dedent(s)) Controller = require 'controller' class foo view: 'baz' class: 'bar' constructor: -> Controller.mix @
As you can see, the global 4-space indentation has been removed, resulting in a string that is ready for further processing or manipulation.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3