Printing a string with a little delay between the chars

前端 未结 7 1553
青春惊慌失措
青春惊慌失措 2020-12-19 23:20

I want a text to be displayed as if it is just being typed. So I need a little delay after every letter.

I tried to do it this way:

import time

text         


        
相关标签:
7条回答
  • 2020-12-19 23:50

    Your example prints them all on separate lines I think (at least on windows). You can use printing to sys.stdout to get around this.

    import time, sys
    for character in text:
        sys.stdout.write(character)
        time.sleep(0.2)
    
    0 讨论(0)
  • 2020-12-19 23:51

    this line:

    print char, time.sleep(0.2)
    

    decodes as "print the value of char, and then print the return value of the function time.sleep() (which is None)".

    You can break them onto separate lines, but the default behavior of print followed by a comma will leave you with spaces between the characters that you probably don't want. If not, look up how to change the behavior of print, or do something like this:

    >>> import sys
    >>> import time
    >>> for char in "test string\n":
    ...    sys.stdout.write(char)
    ...    time.sleep(0.2)
    ...
    test string
    >>>
    
    0 讨论(0)
  • 2020-12-19 23:54
    >>> import time
    >>> import sys
    >>> blah = "This is written slowly\n"
    >>> for l in blah:
    ...   sys.stdout.write(l)
    ...   sys.stdout.flush()
    ...   time.sleep(0.2)
    ...
    This is written slowly
    
    0 讨论(0)
  • 2020-12-19 23:56

    You're printing the return value of time.sleep(0.2) which is None. Put it on a separate line. The comma after "print char" will prevent a newline from being printed but it will introduce a single space after each character.

    Try this instead:

    >>> import sys
    >>> import time
    >>> text = "Hello, this is a test text to see if all works fine."
    >>> for char in text:
    ...     sys.stdout.write(char)
    ...     time.sleep(0.2)
    
    0 讨论(0)
  • 2020-12-20 00:02

    Put the time.sleep in a separate line. With a comma, you are printing its return value as well.

    0 讨论(0)
  • 2020-12-20 00:07

    Thank you all for your help, this is my final code, I made a random timing for the delay as mentioned by Wooble:

    import time
    import sys
    from random import randrange
    
    text = "This is the introduction text."
    
    for c in text:
        sys.stdout.write(c)
        sys.stdout.flush()
        seconds = "0." + str(randrange(1, 4, 1))
        seconds = float(seconds)
        time.sleep(seconds)
    
    0 讨论(0)
提交回复
热议问题