2

I am trying to make the snort effect on the command line.

snort = "SNoooOOO000oooRT"

for char in snort:
            time.sleep(0.1)
            print(char,)

Right now, this code is printing vertically:

S
N
o
o
o
O
O
O
0
0
0
o
o
o
R
T

And when I can get it to print horizontally, I loose the 0.1 seconds wait to create the desired effect.

Cheers

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
J-B
  • 23
  • 1
  • 3
  • 2
    Possible duplicate of [How to print without newline or space?](https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space) – Patrick Artner Mar 02 '18 at 18:20

3 Answers3

3

@Patrick Artner's answer is correct, but I just wanted to add on a use case that will work in certain IDE's as well as the Windows command prompt.

In order to get the desired animation, you have to also include sys, and use sys.stdout.flush() in each iteration of the loop, like so:

import time
import sys

snort = "SNoooOOO000oooRT"

for char in snort:
    sys.stdout.flush()
    time.sleep(0.1)
    print(char,end='')

If you do not do this in the command prompt (or certain IDE's), the program will output the entire string after it has slept for each iteration of the loop.

You can actually also force print() to flush the output buffer by including the flush parameter in your print statement. So you can avoid importing sys if you do this:

print(char,end='', flush=True)
user3483203
  • 50,081
  • 9
  • 65
  • 94
  • Nice one, saw only the burst in my console window but the VS Output window showed it with the delay. – Patrick Artner Mar 02 '18 at 18:44
  • 1
    I believe with VS Code at least, you can add a PYTHONUNBUFFERED=1 environment variable to get around this. But I have not tested this. Still for his use case, I think just adding in `flush=True` is the simplest approach. – user3483203 Mar 02 '18 at 18:45
  • Yep, flush = True did it also for the Popup console :) – Patrick Artner Mar 02 '18 at 18:51
2

Specify the end character of the print command - it defaults to newline if not specificly given. Thats why seperate prints end on new lines:

import time
snort = "SNoooOOO000oooRT"

for char in snort:
    time.sleep(0.1)
    print(char, end = '')

Also useful: the sep='' addon:

print(*[1,2,3,4,5,6,7,8], sep='+')
print(*list("Done"),sep='      ') 

Output:

1+2+3+4+5+6+7+8
D      o      n      e
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1
print(char,)

replace with below line print statement take end argument with any string or char

print(char,end='')
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27