如何在一行之后缩进所有行



示例:

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,但它不能满足我的需要。

我为类似的问题语句使用了上下文管理器:

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类可以自定义。

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

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

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

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

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.

最新更新