Categories
Python Answers

How to print in one line dynamically with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *