Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: print using carriage return and comma not working

I need to print over one line in a loop (Python 3.x). Looking around on SO already, I put this line in my code:

print('{0} imported\r'.format(tot),) 

However, it still prints multiple lines when looped through. I have also tried

sys.stdout.write('{0} imported\r'.format(tot)) 

but this doesn't print anything to the console...

Anyone know what's going on with this?

like image 892
kevlar1818 Avatar asked Jun 13 '12 15:06

kevlar1818


People also ask

How do you print a carriage return in Python?

In Python 3, "print" is a function rather than a special operator. It takes an argument called "end" that specifies the line ending to use. 'Print ("This is a test", end = "\r\n")' prints the sentence with a carriage return and newline character.

How do I stop print from changing lines in Python?

To print without a new line in Python 3 add an extra argument to your print function telling the program that you don't want your next string to be on a new line. Here's an example: print("Hello there!", end = '') The next print function will be on the same line.

What is linefeed in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

How does \r work in Python?

\r takes the cursor to the beginning of the line. It is the same effect as in a physical typewriter when you move your carriage to the beginning and overwrite whatever is there.


1 Answers

If you want to overwrite your last line you need to add \r (character return) and end="" so that you do not go to the next line.

values = range(0, 100) for i in values:     print ("\rComplete: ", i, "%", end="") print ("\rComplete: 100%") 
like image 128
Joris Avatar answered Sep 25 '22 08:09

Joris