Caelan Grgurovic
Caelan Grgurovic

Reputation: 25

replace previous print output with new print output or add characters to previous output

I'm pretty new to Python programming, and I'm attempting to create a simple little game with a little "initialization" on boot up.

I pretty much want it to spell out "Welcome", but with all of the letters popping up every 100ms.

I've got the sleep function down pat, however, rather than adding on each character to the end of the previous line, it is simply printing it all out on a new line.

This is what I'm currently getting:

W
e
l
c
o
m
e
.

I'd prefer it to just be Welcome.

This is my current code:

print("W")
time.sleep(0.1)
print("e")
time.sleep(0.1)
print("l")
time.sleep(0.1)
print("c")
time.sleep(0.1)
print("o")
time.sleep(0.1)
print("m")
time.sleep(0.1)
print("e")

I have looked around, but have failed to understand how to implement the function into Python. So an explanation would be extremely appreciated!

Thanks.

Upvotes: 1

Views: 135

Answers (3)

Ejaz
Ejaz

Reputation: 1632

How about this -

for c in "Welcome":
    print '\b%s' % c,
    time.sleep(0.1)

Upvotes: 0

Xetnus
Xetnus

Reputation: 353

Python's print() function normally prints outputs on a new line, meaning that every time you print something, it appears on another line. To print everything on the same line, as you're asking, use the print() function like this:

print("W", end="")

Notice the second argument which tells Python to continue printing on the same line. The print() function defaults to an ending of \n, or new line. Setting end equal to "" replaced the \n with an empty string.

In the event that you need to use the print() function after you print out "Welcome", the last print() function you use to print out the 'e' should be normal, like this:

print("e")

This way if you print anything after "Welcome", it will print on a new line.

Upvotes: 1

acw1668
acw1668

Reputation: 46669

Use end='' when calling print():

import time
for c in "Welcome":
    print(c, end='')
    time.sleep(0.1)

Upvotes: 2

Related Questions