Python - How to add new line in string

By xngo on June 7, 2019

Overview

New line is defined differently by different operating systems:

  • In POSIX system such as Linux, Unix and Mac OS, it is defined as \n.
  • In MS Windows and DOS, it is defined as \r\n.

Code

#!/usr/bin/python3
# Description: How to add new line in string.
 
import os
 
# Use \n to add new line.
string_with_newline="First line\nSecond line\n"
print(string_with_newline)
 
# Or, use system-dependent new line, os.linesep.
string_with_newline="First line" + os.linesep + "Second line"
print(string_with_newline)

Output

Reference

  • https://docs.python.org/3/library/os.html#os.linesep

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.