1

I want to print only current index in my Python code.

for my_index in range(100):
    print(my_index)

This script currently prints like:

>>>python3 main.py
0
1
2
3
4
...

But I want to print only current my_index in one line without going to new line (or adding space between) like this:

>>>python3 main.py
0

And then 0 cahnges to 1 like so...

>>>python3 main.py
1

I DON'T want it like this:

>>>python3 main.py
0 1 2 3 4 ...

And Python - Print in one line dynamically - Stack Overflow isn't answer to my question.

Thanks in advance!

ahmedg
  • 309
  • 1
  • 2
  • 12
  • The quoted questions is the EXACT duplicate. Use this answer: https://stackoverflow.com/a/3173338/7505395 . You can substitute `sys.stdout.write("\r%d%%" % i)` by `print("\r%d%%" % i, end="")` but you need to keep the `sys.stdout.flush()` afterwards. – Patrick Artner Jul 14 '20 at 11:59
  • @alaniwi without flushing this does not work, because the writing wont be written to the console after every print, but just when convenient. with sys.stdout.flush() its the same. – Patrick Artner Jul 14 '20 at 12:03
  • 1
    @PatrickArtner Hi, sorry I already removed my comment because it largely duplicated yours. Yes you are right about the flush. But also print formatting using `%` isn't really recommended any more. – alani Jul 14 '20 at 12:04

1 Answers1

1

Is this what you're looking for?

You can use sys.stdout.write('\b \b') to delete a character already printed to the console. (Note: won't work in IDLE)

A list of these "special characters" (known as string literals) can be found here

dwb
  • 2,136
  • 13
  • 27