Python 是否有用于取消缩进多行字符串的内置函数?

2025-01-21 09:01:00
admin
原创
152
摘要:问题描述:假设我有字符串s = """ Controller = require 'controller' class foo view: 'baz' class: 'bar' constructor: ->...

问题描述:

假设我有字符串

s = """
    Controller = require 'controller'

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

        constructor: ->
            Controller.mix @
"""

现在,字符串中的每一行都有全局 4 个空格缩进。如果此字符串是在函数内部声明的,则它将具有 8 个空格全局缩进,等等。

Python 是否有一个函数可以删除字符串的全局左缩进?

我希望该函数输出是:

Controller = require 'controller'

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

    constructor: ->
        Controller.mix @"

解决方案 1:

不是内置函数,而是标准库中的函数: textwrap.dedent()

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

Controller = require 'controller'

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

    constructor: ->
        Controller.mix @

解决方案 2:

我知道这个问题已经得到解答了,但还有这种方法:

import inspect

def test():
    t = """
    some text
    """

    return inspect.cleandoc(t)

print(test())

解决方案 3:

textwrap.dedent()接近您想要的,但它没有实现您要求的,因为它有一个前导换行符。您可以包装dedent一个函数,从中删除前导换行符s

def my_dedent(string):
    if string and string[0] == '
':
        string = string[1:]
    return textwrap.dedent(string)

但是textwrap.dedent(),如果您从缩进多行语句生成 Python 源代码,则以特殊方式处理仅包含空格的行是可以的,其中尾随空格无关紧要。

但一般来说,textwrap.dedent()从空格多于“最大缩进”的行中删除多余的空格、从所有空格行中删除空格以及丢弃结束之前的任何空格都是不合适的""",尤其是因为这种行为没有记录并且使用非透明的正则表达式完成。

由于我还生成非 Python 源代码,其中空格通常很重要,因此我使用以下例程。它不处理 TAB 缩进,但它确实为您提供了您要求的输出,而没有前导换行符,textwrap.dedent()失败的地方。

def remove_leading_spaces(s, strict=False):
    '''Remove the maximum common spaces from all non-empty lines in string

Typically used to remove leading spaces from all non-empty lines in a
multiline string, preserving all extra spaces.
A leading newline (when not useing '"""\') is removed unless the strict
argument is True.

Note that if you want two spaces on the last line of the return value 
without a newline, you have to use the max indentation + 2 spaces before 
the closing """. If you just input 2 spaces that is likely to be the 
maximum indent.
    '''
    if s and not strict and s[0] == '
':
        s = s[1:]
    lines = s.splitlines(True) # keep ends
    max_spaces = -1
    for line in lines:
        if line != '
':
            for idx, c in enumerate(line[:max_spaces]):
                if not c == ' ':
                    break
            max_spaces = idx + 1
    return ''.join([l if l == '
' else l[max_spaces-1:] for l in lines])

解决方案 4:

我可以通过回车来做到这一点:

s = """
    
 Controller = require 'controller'
    
    
class foo
    
    view: 'baz'
    
    class: 'bar'
    
    
    constructor: ->
    
        Controller.mix @
    
"""
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   3868  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   2711  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Freshdesk、ClickUp、nTask、Hubstaff、Plutio、Productive、Targa、Bonsai、Wrike。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在项目管理过程中面临着诸多痛点,如任务分配不...
项目管理系统   44  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Monday、TeamGantt、Filestage、Chanty、Visor、Smartsheet、Productive、Quire、Planview。在当今快速变化的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时,常...
开源项目管理工具   42  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Smartsheet、GanttPRO、Backlog、Visor、ResourceGuru、Productive、Xebrio、Hive、Quire。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多企业在选择项目管理工具时常常面临困惑:...
项目管理系统   44  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用