首页 > 解决方案 > 检查 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 行收到语法错误。为什么第一个代码块有效但更简单的第二个代码块失败的任何想法?

标签: pythonpython-3.x

解决方案


在 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关键字而不是同时应用lstriprstrip

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())

推荐阅读