Search code examples
python-3.xprintingindentation

How to achieve multi-line prints using the print() inside a user defined function?


MY CODE

def SimplePrint():
    print("""LINE 1
    LINE 2
    LINE 3""")


SimplePrint()

OUTPUT

LINE 1
    LINE 2
    LINE 3

DESIRED OUTPUT

LINE 1
LINE 2
LINE 3

It Works When I Make The Following Changes To My Code :

def SimplePrint():
    print("""LINE 1
LINE 2
LINE 3""")


SimplePrint()

This However, Disturbs The Indentation.
I Was Wondering If There's Another Way To Do It.


Solution

  • Most of the IDE add the indentation when you press Enter but your python multi line(i.e triple quote) string which is one single string treat the indentation added by the IDE as part of it's literal behavior.

    Understand it this way IDE add the space or tab automatically but python interpreter treat that indentation as space or tab due to multiline string.

               print("""this is demo
    <space/tab>behavior of multi line string""")
    

    Solution: Just escape that indentation added by IDE automatically.

               print("""this is happy demo
    behavior of multi line string""")