Home >Backend Development >Python Tutorial >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!