Menu Close

How to print in one line dynamically with Python?

Sometimes, we want to print in one line dynamically with Python.

In this article, we’ll look at how to print in one line dynamically with Python.

How to print in one line dynamically with Python?

To print in one line dynamically with Python, we can use stdout.write.

For instance, we write

from sys import stdout
from time import sleep

for i in range(1, 20):
    stdout.write('\r%d' % i)
    stdout.flush()
    sleep(1)
stdout.write('\n')

to call stdout.write with the \r character to overwrite the standard out with i.

Then we call flush to update the screen.

Conclusion

To print in one line dynamically with Python, we can use stdout.write.

Posted in Python, Python Answers