【问题标题】:How do I indent all of the lines after a line?如何在一行之后缩进所有行?
【发布时间】:2022-01-04 09:23:22
【问题描述】:

例子:

def print_text():
    print("Here's some text")
    print("Here's some more text")
    print("Here's the rest of the text")

print_text()

# Hypothetical command that indents all of the following text
start_indenting()

print_text()

# Hypothetical command that stops indenting.
stop_indenting()

print_text()

期望的输出:

Here's some text
Here's some more text
Here's the rest of the text
    Here's some text
    Here's some more text
    Here's the rest of the text
Here's some text
Here's some more text
Here's the rest of the text

我正在寻找能够缩进所有文本而不实际更改文本或命令的东西。我不知道我将如何实现这一目标。考虑到我在使用它的程序中的方法有大量的打印语句,编辑给定方法(print_text)中的每个打印语句将是最后的手段。我查看了 textwrap 但它无法满足我的需求。

【问题讨论】:

  • @mkrieger1 我有,但遗憾的是它无法从我所看到的方法中缩进文本。我考虑过用它尝试一些东西,但没有用。
  • 它可以缩进任何文本。
  • 我知道,但它没有我正在寻找的 start_indenting() 和 stop_indenting() 函数
  • 所以你的问题不是如何实际缩进文本,而是如何管理缩进级别大于上下文之外的上下文。

标签: python string


【解决方案1】:

我使用了上下文管理器来处理类似的问题:

class Indenter:
    def __init__(self):
        self.level = 0
        
    def __enter__(self):
        self.level += 1
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.level -= 1
        
    def print(self, text):
        print('\t'*self.level + text)


with Indenter() as indent:
    indent.print('hi!')
    with indent:
        indent.print('hello')
        with indent:
            indent.print('bonjour')
    indent.print('hey')

Indenter可以自定义。

【讨论】:

  • 这也可以通过影响内置print() 函数的方式实现,这将使得使用indent.print() 变得不必要(os 会更容易使用)。
【解决方案2】:

如果您只需要在本地(在单个文件中),您可以覆盖打印功能:

from builtins import print as default_print

print = default_print

def indented_print(*args,  prefix='    ', **kwargs):
    default_print(prefix, *args, **kwargs)

def start_indenting():
    global print
    print = indented_print
    
def stop_indenting():
    global print
    print = default_print
    
def print_text():
    print("Here's some text")
    print("Here's some more text")
    print("Here's the rest of the text")
    
   
print_text()

# Hypothetical command that indents all of the following text
start_indenting()

print_text()

# Hypothetical command that stops indenting.
stop_indenting()

print_text()

您还可以影响所有打印件(不仅在此模块中),使用

def start_indenting(): 
    builtins.print = indented_print

但是您的模块的用户可能不会期望它,并且在出现问题时可能很难追溯。

【讨论】:

  • 仅适用于单行打印。 print("line1\nline2") 只会缩进第一行。
  • @Wups 你是对的:在 indented_print 中使用 textwrap.indent (如其他 cmets 所建议的)将解决此问题。
  • 如何将它与输入一起使用?我注意到输入不适用于这个,这是完全可以理解的,因为这不是我最初的问题,所以我创建了一个,但是你在 indented_print 中执行 default_print(prefix, *args, **kwargs) 我会做什么对于我的输入代码的 default_input()?
  • 你的意思是val=input("type something here:")也应该使用缩进吗?
  • 是的,但我得到了它的工作。我错过了退货声明 lmao。非常感谢您的帮助,这对我正在进行的项目非常有帮助!
【解决方案3】:

没有导入就没有这样的命令。你可以自己编码:

def my_print(text, indent=0, space=4):
    if indent:
        print(indent * space * ' ', end='', sep='')
    print(text)


def print_text(indent = 0):
    my_print("Here's some text", indent)
    my_print("Here's some more text", indent)
    my_print("Here's the rest of the text", indent)


print_text()
print_text(1)
print_text(2)
print_text(3)
print_text(1)
print_text()

输出:

Here's some text
Here's some more text
Here's the rest of the text
    Here's some text
    Here's some more text
    Here's the rest of the text        
        Here's some text
        Here's some more text
        Here's the rest of the text    
            Here's some text
            Here's some more text      
            Here's the rest of the text
    Here's some text
    Here's some more text
    Here's the rest of the text        
Here's some text
Here's some more text      
Here's the rest of the text

显然,如果您的用例需要,您需要添加对多行 text 的处理(可能拆分并将其应用于所有行)以及格式化。

对于导入,您可以使用textwrap.indent

【讨论】:

  • 这行得通,但问题是我使用的方法有大量的打印语句,这会使这变得非常乏味和耗时。我愿意使用导入,但编辑每个语句会很粗糙。但是,如果归根结底,这是一个非常好的解决方案。谢谢!
【解决方案4】:

有很多方法可以实现缩进。 一个简单的示例是创建您自己的打印函数,该函数接受缩进作为参数。

def print_line(text, indent=0):
    line = " " * indent + text
    print(line)

def print_text():
    print_line("Here's some text")
    print_line("Here's some more text")
    print_line("Here's the rest of the text")
    print_line("Here's some text", indent=4)
    print_line("Here's some more text", indent=4)
    print_line("Here's the rest of the text", indent=4)
    print_line("Here's some text")
    print_line("Here's some more text")
    print_line("Here's the rest of the text")

还有像 str.ljuststr.rjust 这样的字符串方法,它们可以用任何字符(包括空格和制表符)填充文本。

【讨论】:

    猜你喜欢
    • 2012-12-18
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多