The carriage return in Python is defined with the escape character \r
. This escape character allows you to reset the position of your cursor to the beginning of a line of text.
When you use this escape character, the text at the beginning will be overwritten with the text after the \r
character.
For example, the following text:
print("Hello World!\rcarry")
Will return:
carry World!
The word Hello
is overwritten with carry
because that is the word specified after the \r
carriage return character.
This escape character is frequently used on Windows system. You might notice the character used with the newline character together, forming \r\n
characters.
This is because Windows keeps backward compatibility with MS-DOS, which requires both \r
and \n
to be present.
On the other hand, UNIX-based OSes like Linux and macOS are okay with using only \n
character to create a new line.
A computer is different than a typewriter. When you add a new line to the text, most likely you also want the program to reset the position of the cursor as well.
This is why the carriage return character is rarely used today. Even on Windows 11, the \n
character will work fine when you want to put text in a new line.
And now you’ve learned how the carriage return escape character works in Python. Nice work! 🙌