2

I've just started learning python from the source learnjavathehardway.

There was a "fun" code that goes as follows

while True:
    for i in ["/","-","|","\\","|"]:
        print "%s\r" % i,

Now what it does is that at the same place in my console, it prints the different character one by one. (Try it yourself if you did not get what I said)

Basically,it prints / - | \ | in quick succession, at the same place.

If I remove comma from the end of print statement, it prints each character in a new line.

Now I want to know, why is it printing out at the same place? And not one after the other? Thanks

Kraken
  • 23,393
  • 37
  • 102
  • 162
  • If the site is called *Learn **Java** the Hard Way,* don't be surprised if they can't teach you Python. – tripleee May 19 '21 at 03:50

1 Answers1

8

That's because of the \r, which is the carriage return <CR> character in ascii. It basically resets the cursor to the start of the line.

The comma at the end of that line is because in python 2.7, the print statement adds a newline. Using the comma, the newline is not added.

In python 3.x, print is no longer a statement but a function. You can provide the end keyword-argument to print() to determine the ending character, which defaults to a newline, \n.

msvalkon
  • 11,887
  • 2
  • 42
  • 38
  • Ohh, did not see that. Thanks alot. :) – Kraken Apr 26 '14 at 19:17
  • Wow, didn't know that `\r` and `,` in print worked that way - to print things in the same line (in Python2). Is the `\r`+`,` behaviour different on Mac since the newlines are different codes? Since it's [not reading from a file](http://stackoverflow.com/q/4599936/1431750) I wouldn't think it's automatically handled for a `print` statement/function. – aneroid Apr 26 '14 at 19:29
  • I believe that the functionality is cross-platform. The `carriage return` is the same in all of the three major platforms, it's just the line separator that differs (from `\r\n` to `\n`), e.g windows prepends the carriage return to the line feed. – msvalkon Apr 26 '14 at 19:35