简体   繁体   中英

How do I indent all of the lines after a line?

Example:

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()

Desired Output:

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

I'm looking for something that indents all text after it without actually changing the text or commands. I have no clue how I would achieve this. Editing each print statement in the given method (print_text) would be a last resort considering my method in the program I'm using this for has a ton of print statements. I've looked at textwrap but it isn't able to do what I need.

I have used a context manager for a similar problem statement:

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')

Class Indenter can be customized.

There is no such command without imports. You can code it yourself:

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()

Output:

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

Obviously you would need to add handling for multiline text (maybe splitting and applying it to all lines) as well as for formatting if your use case needs those.

With imports you can usetextwrap.indent .

If you only need it locally (in a single file), you may override the print function:

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()

You could also affect all prints (not only in this module), with

def start_indenting(): 
    builtins.print = indented_print

but users of your module may not expect it, and it might be hard to traceback in case of problem.

There are tons of ways to implement indentation. An simple example would be creating your own print function that accepts indentation as an argument.

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)

There are also string methods like str.ljust and str.rjust which can pad text with any character including spaces and tabs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM