在运算符中没有像我期望的那样使用字符串列表

时间:2016-01-13 06:08:05

标签: python python-2.7 if-statement

我用样本声明把头发拉了出来。我的代码就是这个。

Test2 = selector2.xpath('string(//div[@class="js-shipping-slide-panel shipping-slide-panel-section product-buying-table-row-alt"])').extract()
print "Test2", Test2

我得到了输出:

Test2 [u'    Shipping not available     \n      Shipping   This item is not      available for shipping.    \n']

那是完美的。所以这是我的样本If Statement我正在尝试

if "shipping" in Test2:
    print "Found it"
else:
    print "It's Not There"

我得到的结果是不存在。我甚至将输出和硬编码的Test2复制为

Test2 = "u'    Shipping not available     \n      Shipping   This item is not      available for shipping.    \n'"

并运行相同的if语句并且它有效,给我一个结果"找到它"。我在这里错过了什么?感谢。

2 个答案:

答案 0 :(得分:1)

您可以在输出中看到Test2不是字符串。它是一个包含字符串的列表。试试if "shipping" in Test2[0]。 (如果xpath查询返回多个结果,您还应该考虑要执行的操作。)

答案 1 :(得分:0)

你有一个单身list。这意味着您必须检查'shipping'是否在list的第一个元素中。

if "shipping" in Test2[0]:

您的其他测试是检查整个字符串是否包含实际上不属于原始字符串的额外环绕引号,是否在list中,当然,它不是。您正在检查的list包含一个不包含引号的字符串:

"u'    Shipping not available     \n      Shipping   This item is not      available for shipping.    \n'"

不是

u'    Shipping not available     \n      Shipping   This item is not      available for shipping.    \n'

前一个字符串的第一个字符是字母u。后一个字符串的第一个字符是空格字符。您必须将前一个字符串发送到ast.literal_eval()之类的解析器以生成后一个字符串(但正确的做法是将测试字符串正确地硬编码,同时考虑到Python语法)。