1

I am matching an empty value with an array element which has one value in it and the array does not have any empty values. However, still this script works.

import re

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

How come it is working when b is empty and the array element is 'Arunsdsdds' (which has no empty value in it)?

miradulo
  • 28,857
  • 6
  • 80
  • 93
Mounarajan
  • 1,357
  • 5
  • 22
  • 43
  • An empty string is contained in every non-empty string (and obviously in any other empty string). Use `==` instead of `in`. – DeepSpace Jul 05 '16 at 06:59
  • Possible duplicate of [Why Python returns True when checking if an empty string is in another?](http://stackoverflow.com/questions/27603885/why-python-returns-true-when-checking-if-an-empty-string-is-in-another) – tripleee Jul 26 '16 at 06:22

3 Answers3

2

An empty string is always considered to be part of any string:

>>> "" in "abcd"
True
sidney
  • 757
  • 1
  • 6
  • 10
1

The empty string is a substring of every string in Python. This is because the substring of length 0 of any string s[0:0] is equal to the empty string.

A proper way to check if a string s is not empty is simply if not s:, as empty strings are "falsey".

To check if something is equal to the empty string, just use == as opposed to in.

miradulo
  • 28,857
  • 6
  • 80
  • 93
0

tristan gives a detailed answer in the post Why Python returns True when checking if an empty string is in another?. The important sentence is there:

Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

You find this sentence in the Python 2.7. reference, article Expressions in the chapter Comparisons. Or for Python 3 in Expressions, chapter Membership test operations.

Community
  • 1
  • 1
Humbalan
  • 677
  • 3
  • 14