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

0

Issue

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.

Solution

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.

Answered By – Demi-Lune

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More