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



我喜欢将两个打印语句保存在 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='')

print(x) 函数隐式

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

所以,你不能做

 stored = print(x)

相反,写

stored_value = str(x)
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()

最新更新