How can I indicate a newline in a string in Python, so that I can write multiple lines to a text file?

How can I indicate a newline in a string in Python, so that I can write multiple lines to a text file?

You can also use the escape character \n directly in the string. This method is simple and straightforward. You insert \n wherever you want a newline in your string.

When the string is written to a file or printed, \n will be interpreted as a newline character, causing the text to be displayed on separate lines.

text = “Line 1\nLine 2\nLine 3”

Also, triple quotes as well!

Triple quotes allow you to create multiline strings in Python. Inside triple quotes, newlines are preserved as-is, so you can write your text with line breaks directly in the string. This makes it easy to write and read multiline strings in your code.

text = """Line 1
Line 2
Line 3"""

Hey, you can create a multiline string by concatenating multiple strings together, each representing a line of text. By adding \n between the strings, you effectively insert newline characters between the lines. While this method works, it can be less readable and more cumbersome than using triple quotes for multiline strings.

text = "Line 1" + "\n" + "Line 2" + "\n" + "Line 3"