Mounarajan
Mounarajan

Reputation: 1437

How come empty value is matching with array value in python

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

Upvotes: 1

Views: 143

Answers (3)

Humbalan
Humbalan

Reputation: 717

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.

Upvotes: 0

miradulo
miradulo

Reputation: 29720

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.

Upvotes: 1

sidney
sidney

Reputation: 827

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

>>> "" in "abcd"
True

Upvotes: 1

Related Questions