【问题标题】:How come empty value is matching with array value in python空值如何与python中的数组值匹配
【发布时间】:2016-11-06 21:51:27
【问题描述】:

我将一个空值与一个数组元素匹配,该数组元素中有一个值,并且该数组没有任何空值。但是,这个脚本仍然有效。

import re

b = ""
links_check_arr = ['Arunsdsdds']
for links_find in links_check_arr:
    if b in links_find:
        print  links_find
        print b

b 为空且数组元素为'Arunsdsdds'(其中没有空值)时,它是如何工作的?

【问题讨论】:

标签: python string python-2.x


【解决方案1】:

空字符串总是被认为是任何字符串的一部分:

>>> "" in "abcd"
True

【讨论】:

    【解决方案2】:

    空字符串是Python中每个字符串的子字符串。这是因为任意字符串s[0:0]的长度为0的子字符串等于空字符串。

    检查字符串s 是否不为空的正确方法就是if not s:,因为空字符串是“假的”。

    要检查某些内容是否等于 到空字符串,只需使用== 而不是in

    【讨论】:

      【解决方案3】:

      tristan 在Why Python returns True when checking if an empty string is in another? 的帖子中给出了详细的回答。重要的一句话就在那里:

      空字符串总是被认为是任何其他字符串的子字符串 字符串,所以 "abc" 中的 "" 将返回 True。

      你可以在 Python 2.7 中找到这句话。参考,比较一章中的文章Expressions。或Expressions, chapter Membership test operations 中的 Python 3。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-24
        • 2014-03-27
        • 1970-01-01
        • 1970-01-01
        • 2014-09-28
        相关资源
        最近更新 更多