开发者社区> 问答> 正文

Python 3.6 sleep()在同一个字符串内的不同睡眠时间取决于字符

在python 3.6中,这是我的代码。我的问题是我得到了字符之间的延迟,但我没有在句子之间得到更长的延迟。

import time
import sys

def delay_print(s):

for c in s:
    if c != "!" or "." or "?":
        sys.stdout.write(c)
        # If I comment out this flush, I get each line to print
        # with the longer delay, but I don't get a char-by char 
        # delay
        # for the rest of the sentence.
        sys.stdout.flush()
        time.sleep(0.05)
    elif c == "!" or "." or "?":
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(3)

delay_print( """

Hello.
I want this to have an added delay after sentence-ending 
punctuation?
But I also want it to have a shorter delay after each character 
that isn't one of those chars.
This is supposed to mimic speech patterns. Like if you've ever 
played SNES Zelda: A Link to the Past.
Why isn't this code doing what I want it to?.
What I've written is broken and I don't know why!

""")

展开
收起
一码平川MACHEL 2019-02-28 14:21:27 2014 0
2 条回答
写回答
取消 提交回答
  • 跟这没有关系

    2019-11-18 18:04:16
    赞同 展开评论 打赏
  • 你的or条款没有做你认为它正在做的事情。第一个检查这三件事中的任何一件是否为True:

    character != "!"
    bool(".")
    bool("?")
    请注意,2和3始终为真。

    如果声明短路评估。如果字符输入是.,它将检查条件1并发现它是假的。然后它将包括评估中的条件2 False or "."。因为"."总是如此,它会短路和返回".",其评估结果为真。自己尝试一下,键入False or "."解释器,你会发现它返回"."。

    就个人而言,我会用这样的set实现来做到这一点:

    if c not in {"!", ".", "?"}:

    2019-07-17 23:29:45
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载