【问题标题】:How to print one character at a time on one line?如何在一行上一次打印一个字符?
【发布时间】:2012-02-12 03:04:15
【问题描述】:

如何将字符串“hello world”打印在一行上,但一次打印一个字符,以便在每个字母的打印之间存在延迟?我的解决方案要么导致每行一个字符,要么一次延迟打印整个字符串。这是我得到的最接近的。

import time
string = 'hello world'
for char in string:
    print char
    time.sleep(.25)

【问题讨论】:

    标签: python


    【解决方案1】:

    这里有两个技巧,您需要使用流将所有内容放在正确的位置,还需要刷新流缓冲区。

    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")
    

    【讨论】:

    • 为什么是字符串插值? sys.stdout.write(c) 在我的系统上运行良好。
    【解决方案2】:

    这是 Python 3 的一个简单技巧,因为您可以指定 print 函数的 end 参数:

    >>> import time
    >>> string = "hello world"
    >>> for char in string:
        print(char, end='')
        time.sleep(.25)
    
    
    hello world
    

    玩得开心!结果现在是动画的!

    【讨论】:

    • 有理由不使用这个解决方案吗?它看起来简单而优雅。
    • 一个很小的。默认输出是缓冲的,所以你想要添加 flush=True 像这样:print(char, end='', flush=True)
    【解决方案3】:
    import sys
    import time
    
    string = 'hello world\n'
    for char in string:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(.25)
    

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题,并提出了不同的解决方案。 刷新缓冲区没有帮助。操作系统:Windows 10,python 3.7.4 64 位

      代码无效

      [while loop]
          [if statement]
             try:               
                  playsound(path)              
                  time.sleep(60)
      

      工作代码

      import time
      from time import sleep
      [while loop]
          [if statement]
             try:               
                  playsound(path)              
                  sleep(60)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-21
        相关资源
        最近更新 更多