如何将打印函数的输出存储到python中的变量?

时间:2021-06-30 09:57:28

标签: python python-3.x

我编写了一个函数,可以在 python 中将输出打印到屏幕上。我希望在调用函数时将打印语句作为返回值。

    def printer:
        print("Statement 1")
        print("Statement 2")
        ....

代替上面的

    def printer:
        return  x
    print(printer())

1 个答案:

答案 0 :(得分:1)

您需要通过变量打印语句并将其存储在列表中,有点像这样:

def printer():
    printed_lines = []

    line = "Statement 1"
    print(line)
    printed_lines.append(line)

    line = "Statement 2, etc"
    print(line)
    printed_lines.append(line)

    return printed_lines