How would one print the string “hello world” onto one line, but one character at a time so that there is a delay between the printing of each letter? My solutions have either resulted in one character per line, or a delayed printing of the entire string at once. This is the closest I’ve gotten.
import time
string = 'hello world'
for char in string:
print char
time.sleep(.25)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Two tricks here, you need to use a stream to get everything in the right place and you also need to flush the stream buffer.
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.25)
delay_print("hello world")
Method 2
Here’s a simple trick for Python 3, since you can specify the end parameter of the print function:
>>> import time
>>> string = "hello world"
>>> for char in string:
print(char, end='')
time.sleep(.25)
hello world
Have fun! The results are animated now!
Method 3
import sys
import time
string = 'hello worldn'
for char in string:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.25)
Method 4
I had the same problem and came with different solution. Flushing buffer did not help. OS: Windows 10, python 3.7.4 64-bit
not working code
[while loop]
[if statement]
try:
playsound(path)
time.sleep(60)
working code
import time
from time import sleep
[while loop]
[if statement]
try:
playsound(path)
sleep(60)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0