Home > Article > Backend Development > 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 @ """
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.
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!