使用相同的三行代码打印多行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用相同的三行代码打印多行相关的知识,希望对你有一定的参考价值。

下面的代码每隔0.1秒钟逐个字母打印欢迎文本。

welcome = ("Welcome")

for character in welcome:
    print (character, end = "", flush = True)
    sleep(0.1)

通常,如果我想打印几样东西(在这种情况下,欢迎和您好,我会这样做:

welcome = ("Welcome")
hello = ("Hello")

for character in welcome:
    print (character, end = "", flush = True)
    sleep(0.1)

for character in hello:
    print (character, end = "", flush = True)
    sleep(0.1)

但是每次我想要换行时都键入此命令效率不高,因为这会浪费大量时间和空间。

for character in hello:
        print (character, end = "", flush = True)
        sleep(0.1)

有没有办法我只能以某种方式使用其中之一

for character in hello:
            print (character, end = "", flush = True)
            sleep(0.1)

打印许多不同的行,如下所示:

hello = ("How are You")
welcome = ("Welcome")
nice = ("Awesome")
答案
from time import sleep hello = ("How are You") welcome = ("Welcome") nice = ("Awesome") messages = [hello, welcome, nice] for message in messages: for character in message: print (character, end = "", flush = True) sleep(0.1) print('')

输出看起来像这样:

你好吗

欢迎

很棒

另一答案
def fancy_print(text): [print_and_wait(c) for c in text] def print_and_wait(char): from time import sleep print(char, end='', flush=True) sleep(0.1) if __name__ == '__main__': hello = "How are You" fancy_print(hello) welcome = "Welcome" fancy_print(welcome) nice = "Awesome" fancy_print(nice)
另一答案
welcome = "Welcome" hello = "Hello" list = [welcome,hello] def my_function(word): for character in word: print(character, end="", flush=True) sleep(0.1) def my_function_list(list): for word in list: my_function(word) my_function_list(list)
另一答案
def print_char_by_char(word): for character in word: print (character, end = "", flush = True) sleep(0.1)

然后使用它:

print_char_by_char("How are You")
print_char_by_char("Welcome")
print_char_by_char("Awesome")

以上是关于使用相同的三行代码打印多行的主要内容,如果未能解决你的问题,请参考以下文章

剑指offer系列49:把二叉树打印成多行

我的Android进阶之旅NDK开发之在C++代码中使用Android Log打印日志,打印出C++的函数耗时以及代码片段耗时详情

在具有多行标题的选项卡上设置片段

argparse 代码片段只打印部分日志

Python代码阅读(第25篇):将多行字符串拆分成列表

剑指offer系列——59/60.按之字形顺序打印二叉树/把二叉树打印成多行