So in my studies I’m finding the following print statements being used interchangeably to shift to a new line:
Can they actually be used interchangeably or is there a best practice behind each one? How do they differ technically?
print(" ") prints a single space and then starts a new line. That means that the line will have ended with a space, which you probably won’t notice unless it happens to wrap onto the next line because the cursor is already right at the end of the line.
print() starts a new line.
print("\r") moves the cursor to the start of the current line and then starts a new line. It’s probably pointless moving to the start of the current line if you’re then just starting a new line.
In addition to the above, you’ll also see the likes of
print("A message\n") The slash n (or escape ‘n’) prints an additional new line; one more than the
print() function will deliver by default.
I’m not sure whether you’d see
print(" ") or
print("") more. The latter is effectively equivalent to
print(), but might be seen in some older code as it will behave correctly even on Python 2.5 or older (yes, seriously ancient). Printing a space before moving to the next line is usually unnecessary, as MRAB mentioned, but it can be useful if you’ve previously printed something with
end="\r" and now want to overwrite that. For example:
for char in itertools.cycle("/-\\|"):
if work_all_done(): break
print(" ") # Move to next line, but also clear the spinner
I’d say that
print("\r") is usually useless, but maybe someone wants to write out a CR/LF pair only under certain circumstances?? Normally, if you need CR/LF line endings (eg if you’re printing down a network protocol rather than to a console), it’s best to configure things rather than have to remember to put a “\r” everywhere.
And of course,
print() is the simplest and most obvious way to output a blank line, and should be the one most used.