【问题标题】:I have a section of code from a text game project that isn't working as expected我有一段来自文本游戏项目的代码没有按预期工作
【发布时间】:2019-10-14 18:24:36
【问题描述】:

我有一段代码如下所示:

for l in blah: sys.stdout.write(l) sys.stdout.flush() time.sleep(0.025)

这会在打印语句中打印的每个字符之间增加一点延迟,该语句分配给变量blah。但是,如果 print 语句中存在变量,例如:

blah = "\n", player_name, ", you must save this land from the virus that has blighted us.\n"

那么打印语句将不会像我想要的那样打印,而是像正常的打印语句那样打印。

我希望打印语句会像被逐行快速键入一样打印出来,但实际上打印语句是一次性打印出来的。

【问题讨论】:

  • "\n", player_name, ", you must save this land from the virus that has blighted us.\n" 是一个由三个元素组成的 元组,其中两个是字符串。所以,blah[2] 是字符串 ", you must save this land from the virus that has blighted us.\n"
  • blah 如您所见是元组而不是字符串。您可以使用 stackoverflow.com/questions/19641579/… 中提到的内容将其转换为字符串

标签: python


【解决方案1】:

您可以使用“f-string”:

blah = f"\n{player_name}, you must save this land from the virus that has blighted us.\n"

这允许您将当前范围内的变量(例如player_name)直接替换到您正在构建的字符串中。如果player_name'Alex',那么生成的blah 将是"\nAlex, you must..."


所做的是将tuple 分配给blah。然后,当您尝试对其进行迭代时,您会得到“元组的每个元素”,而不是“字符串的每个字符”。内置的 print() 函数允许您提供任意数量的参数,并且在内部将自身解析为元组,但大多数函数不允许您这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-30
    • 2022-10-06
    • 1970-01-01
    • 2018-07-20
    • 2020-11-10
    • 2021-12-11
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多