python - 检查 IF 中的空 str
问题描述
我有下面的代码:
for result in s.find_all(attrs={"ng-bind-html":"entry.result"}):
if result.text.rstrip().lstrip() == '':
0
else:
l_result.append(result.text.rstrip().lstrip())
这很好用,我需要 IF 在加载到列表之前检查空白结果值。
我最初是这样写的:
for result in s.find_all(attrs={"ng-bind-html":"entry.result"}):
if result.text.rstrip().lstrip() <> '':
l_result.append(result.text.rstrip().lstrip())
但我在 IF 行收到语法错误。为什么第一个代码块有效但更简单的第二个代码块失败的任何想法?
解决方案
在 python 中,您只需使用not
否定词。<>
在 python 3 中不是有效的 python 语法。(更新)
你的代码:
for result in s.find_all(attrs={"ng-bind-html":"entry.result"}):
if result.text.rstrip().lstrip() <> '': #invalid
l_result.append(result.text.rstrip().lstrip())
if result.text.rstrip().lstrip() <> '':
可以正确写为
if not result.text.rstrip().lstrip() == '':
或者更好:
if result.text.rstrip().lstrip():
这依赖于非空字符串的真实性。(空字符串为 Falsey,非空字符串为 True)
请注意,您也可以只使用strip
关键字而不是同时应用lstrip
和rstrip
for result in s.find_all(attrs={"ng-bind-html":"entry.result"}):
if result.text.strip(): #checks if non empty.
l_result.append(result.text.strip())
推荐阅读
- mysql - 使用 FORCE INDEX 确保在计算用户变量之前使用 GROUP BY 和 ORDER BY 对表进行排序
- c++ - OpenGL半圆旋转和四分之一圆
- c# - FileOpenPicker 在 Xbox One 上始终返回 null
- python - Python - 如何使函数内部使用的变量具有迭代值?
- reactjs - 第三方组件在尝试更新时将状态重置为初始值
- java - 如何在 JSP SQL Select 语句中传递来自控制器的employeeId?
- twitter-bootstrap - 折叠时看不到我的下拉按钮
- javascript - SVG 中的 ForeignObject 不起作用 - React
- javascript - 我的弹出窗口在页面顶部打开
- c++ - 覆盖虚函数不同于 C++