How to Add CRLF to a String in Python

By Jonah Quant

Carriage Return (CR) is a control character that causes the text cursor to move to the beginning of the line. Line Feed (LF) is another control character that causes the cursor to move to the following line. Different operating systems follow different conventions that use one or both of those characters to signal the end of a text line. For example, on the Windows operating systems, a line of text ends with a CR followed by a LF. You can terminate strings with a CR/LF combination to make your Python code follow this convention.

Step 1

Compute the value of the string you want to output and assign it to a Python variable, as in the following sample code:myString = "Average programmer salary"

Step 2

Add the CR control character to the end of the string by using Python's "+" string concatenation operator:myCRString = myString+'\r'

Step 3

Add the LF control character to the end of the string by using Python's "+" string concatenation operator:myCRLFString = myCRString+'\n'In the example, variable "myCRLFString" contains the initial string value with CR and LF added for correct output.

References & Resources