开发者社区> 问答> 正文

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

一码平川MACHEL 2019-02-28 14:21:27 371

在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!

""")

网络架构 Python
分享到
取消 提交回答
全部回答(1)
  • 一码平川MACHEL
    2019-07-17 23:29:45

    你的or条款没有做你认为它正在做的事情。第一个检查这三件事中的任何一件是否为True:

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

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

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

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

    0 0

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题