Typing effect in Python

前端 未结 7 1845
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 00:05

I want to make such program which reads characters from a string and prints each character after some delay so its look like typing effect.

Now my problem is sleep f

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-13 00:33

    You have to flush the stdout at each loop, to empty the buffer:

    import sys
    
    from time import sleep
    
    words = "This is just a test :P\n"
    for char in words:
        sleep(0.5)
        sys.stdout.write(char)
        sys.stdout.flush()
    

    Without this, it just stored your string in the buffer and wait for an \n (or sufficient amount of characters to print), which come at the end of your loop....

    More info :

    • How to flush output of Python print?
    • Usage of sys.stdout.flush() method

提交回复
热议问题