Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading