Python print r not working

I am trying to print in the exact same spot:

for i in range[10]:
    print["ok\r"],

However, this prints 10 oks in different lines:

ok
ok
...

I tried putting the \r in the front of the string as well. In this case, I get a blank line then 10 oks:

[blank]
ok
ok
...

I also tried the following

import sys

for i in range[10]:
    sys.stdout.write['ok\r']
    sys.stdout.flush[]

But I get the same exact thing. I am on Python 2.7 in pyscripter, what am I doing wrong? I also tried in IDLE, and there 'okokokokokokokokokok' is the result when \r is on the end, and ' ok ok ok ok ok ok ok ok ok ok' is the result when it is in the front.

Edit: I am on windows 7

Any help is highly appreciated!

Carriage returns don't [normally] directly override the last line.
Subsequent text will overwrite the already printed text [or parts of it].
At least with forced flushing, it should print some-thing.

The common use case is to continuously print the state of the program:

print["initializing", end="\r"]
# ...
print["fetching data", end="\r"]
# ...
for train_step in range[1000]:
  # ...
  print["training | step:", train_step, "| loss:", loss, end="\r"]
# ...
print["accuracy", accuracy]

This way, you don't spam the notebook output with pages of redundant logging.

FIX: To fix the carriage return now working issue in your IDE, you must directly use the terminal to execute the code instead of using the built-in output console provided by the IDE.

  • Problem Formulation
  • Solution
    • Method 1
    • Method 2
    • Method 3
  • Solving the Issue in PyCharm
  • Conclusion

Problem Formulation

It is a common issue in many IDEs, including VS Code and PyCharm, wherein the carriage return character [‘\r’] does not work properly within the print statement.

Example: Consider the following code where we are attempting to overwrite the previous print to the same line:

import time
li = ['start', 'Processing result']
for i in range[len[li]]:
    print[li[i], end='\r']
    time.sleep[2]
print[end='\x1b[2K'] # ANSI sequence to clear the line where the cursor is located
print['Terminate']

Expected Output:

Actual Output: Unfortunately, when we execute this code in VS Code and run it in the OUTPUT console, this is how the output looks:

🛑 Thus, the actual output defeats the purpose of the code as the print statement displays the strings in new lines, which is exactly what we want to avoid.

Reason: The question here is – “Is the code wrong?” Well, there is no issue with our code. Let’s get to the root of the problem.

The OUTPUT console in VS Code exhibits a slightly different behavior than the standard output terminal. Some GUI-based IDEs don’t work properly for the Carriage return character [“\r“].  Hence, even though the code is correct, the output console of the IDE is not working properly for the carriage return within the print statement.

📌Highly Recommended Read: How to Overwrite the Previous Print to Stdout in Python?

Solution

[FIXED] Carriage return Not Working with Print in VS Code

The straightforward solution to this problem is to run the code in the standard output terminal instead of executing the code in the output console.

Note: If you are facing problems with buffering the output you can use the flush='True' parameter within the print statement as shown below.

import time
li = ['start', 'Processing result']
for i in range[len[li]]:
    print[li[i], end='\r', flush=True]
    time.sleep[2]
print['Terminate']

Let’s dive into the different ways to execute the code in the terminal to get the desired output:

Method 1

  • Select Terminal
  • Select the PATH, which contains the .py script. In my case, it is: D:\VS Code Python Scripts. So this is the command to navigate to this path [in WINDOWS]: cd 'D:\VS Code Python Scripts'
    • Note that I have used ' ' to enclose the path to avoid any command-line error because of the spacing in the filename.
  • Once you are at the specified Path, use the normal Python command to run your script: python same_line_print.py

Output:

Method 2

  • Right-click on the code
  • Select Run Python file Terminal

Method 3

If you are using the Code Runner Extension to run your code in VS Code:

  • Click on the  down arrow button just beside the Run button. A drop down menu appears.
  • Select Run Python File [Don’t select Run Code]

Solving the Issue in PyCharm

The same issue can be observed in the PyCharm IDE as well. The solution in this case is quite similar, i.e., run the code directly in the terminal.

  • Select Terminal
  • Type the normal Python command to execute the program:
    • python 'carriage return.py'

Conclusion

Thus, the bottom line is – Though the code is correct, it is the console of the IDE that misbehaves and obstructs the carriage return, which denies us the kind of output we want. Hence, the simple solution to this is to use the terminal to run your code from within the IDE.

Related Read: Best Python IDE and Code Editors [Ultimate Guide]

I hope this tutorial helped you. Please subscribe and stay tuned for more solutions and tutorials. Happy learning! 🙂

To become a PyCharm master, check out our full course on the Finxter Computer Science Academy available for free for all Finxter Premium Members:

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork
LinkedIn

What does \r do in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

How do I print on the same line in python R?

Use a carriage return "\r" to print over the same line Use the syntax print[string, end = "\r"] to make the next stdout line begin at the beginning of the current line.

How do I print numbers left to right in Python?

Number Formatting Using Format[] Method in Python Numbers can also be left, right, or centre aligned using python format[] method. For displaying a number with left alignment, we use the “:

Chủ Đề