Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace/update print statement instead of new line (python)

If I wanted to print two statements in Python (3) on separate lines, I would do something like this:

print('Doing something...')

# Do task

print('Done!')

Which would print to the console:

$ Doing something...
$ Done!

Question 1

How could I get the message to stay on the same line even though the two parts are on different lines and have code in between them.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The result would be as follows where Done! appears once the task is completed.:

$ Doing something ... Done!

Question 2

How could I achieve this where at first a different message is in place of Done! and then changes when it is complete:

This would mean the message would change from:

$ Doing something ... [in progress]

to

$ Doing something ... Done!

And this would happen all in the same line

>Solution :

Question one, and indeed question 2 as well, can be solved by looking into the end key word argument for the print function in python.
In question one specifically, we can solve this with

print("Doing something ... ", end = "")
print("Done!")

Which I believe should return exactly what you want. Here we overwrote the standard value of end (which is "\n") with a blank string where we didnt need the new line, hence the tagging on the end of the current line for the next print function. For question two, we can do

print("Doing something ... [in progress]", end = "\r")
print("Doing something ... Done!        ")

where the end key word argument is given the value "\r", which tells it to return to the beginning of the line. Edit: Note the extra trailing whitespace to overwrite the rest of the previous message.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading