python - 带打印的翻转功能返回
问题描述
可能我不正确,但我无法弄清楚为什么会发生这种情况。
突破我正在尝试编写的脚本,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
解决方案
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
推荐阅读
- jquery - 我如何使用 jquery 计算 asp.net mvc 上的文本框中留下的字符
- jquery - jquery 输入类型文件 *.xlsx
- php - php核心贝宝sdk
- java - Maven 资源插件不会过滤掉嵌套在 ${} 中的自定义分隔符
- spring-boot - PCF 每 5 分钟报告一次应用程序崩溃
- tensorflow - 了解 export_tflite_ssd_graph.py
- django - 仅当用户发送消息时才保存聊天线程
- c# - 如何在 C# 中查询复杂的 n:m 关系以获取 IEnumerable
- python - 通过 requirements.txt 在 Azure Databricks 上维护库/包
- react-native - React Native - Animated.View 内的可触摸不透明度是背景列表视图的触发事件