Python如何在变量中存储打印语句?

时间:2019-04-11 09:00:51

标签: python printing

我喜欢将两个打印语句保存在2个不同的变量中。 我该怎么办?

 with open(file_to_open) as f:

    for line in f:
        # split the line
        line = line.strip()
        columns = line.split(",")

        if columns[0] == "1":
           print(line, end='')
        if columns[0] == "2":
            print(line, end='')

2 个答案:

答案 0 :(得分:0)

print(x)函数隐式

  1. 呼叫str(x)
  2. 显示它
  3. 返回None

所以,你不能做

 stored = print(x)

相反,写

stored_value = str(x)

答案 1 :(得分:0)

with open(file_to_open) as f:
    for line in f:
    # split the line
        line = line.strip()
        columns = line.split(",")

        if columns[0] == "1":
            def af(line=line):
                print(line, end='')
            a = af
        if columns[0] == "2":
            def bf(line=line):
                print(line, end='')
            b= bf

使用闭包,可以在调用时保存print语句及其参数。然后,您可以在以后任何时候调用此保存的语句。

a()  
b()