首页 > 解决方案 > 带打印的翻转功能返回

问题描述

可能我不正确,但我无法弄清楚为什么会发生这种情况。

突破我正在尝试编写的脚本,OS Windows 10,Visual Studio Code,Python 3.7

我编写了一个带有函数的类,该函数应该打印到控制台和 .txt 文件中,一些由网页抓取的数据。

这里的功能:

def create_alimento(Componenti_principali):  
    for col1, col2 in zip(soup.select('#tblComponenti > tr.testonormale > td:nth-of-type(1)'), soup.select('#tblComponenti > tr.testonormale > td:nth-of-type(2)')):
        print('{: <70} {}'.format(col1.text, col2.text))

控制台的输出没有任何问题,它完成了自己的工作,对我来说似乎很清楚。我不明白的是 .txt 输出,它出现了一个错误,TypeError 准确地说:write() 参数必须是 str,而不是 None。

它清楚地表明我要打印的类(也包括上面的函数)是 None 类型,因此是主要对象。

现在,问题是,如果我翻转:

print('{: <70} {}'.format(col1.text, col2.text))

和 :

return('{: <70} {}'.format(col1.text, col2.text))

...函数对象类型是“字符串”,不再是 NoneType。

如果一切正常,我不会指出它,显然,使用return而不是print,不会给出 .txt 输出。

有人知道这里发生了什么吗?以及在控制台和 .txt 中打印相同输出的任何建议?

提前致谢, Mx

标签: pythonprintingreturn

解决方案


Areturn从函数返回一个值,例如:

def f():
    return 7

seven = f()
# value of seven is now 7

打印不返回值,例如:

def f():
    print(7)  # at this point "7" is printed to the standard output

seven = f()
# value of seven is now None

如果你想打印一个值并返回一个值,你应该这样做,例如:

def f():
    print(7)  # at this point "7" is printed to the standard output
    return 7

seven = f()
# value of seven is now 7

顺便说一句,只返回值会是一个更好的设计。如果需要,您可以随时从外部打印它,即:

def f():
    return 7

seven = f()
# value of seven is now 7
print(seven)  # at this point "7" is printed to the standard output

推荐阅读