Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"IN" operator with empty strings in Python 3.0 [duplicate]

As I am going through tutorials on Python 3, I came across the following:

>>> '' in 'spam'
True

My understanding is that '' equals no blank spaces.

When I try the following the shell terminal, I get the output shown below it:

>>> '' in ' spam '
True

Can someone please help explain what is happening?

like image 271
Brightlights Avatar asked May 15 '16 01:05

Brightlights


People also ask

How do you handle an empty string in Python?

Use len to Check if a String in Empty in Python # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string! Keep in mind that this only checks if a string is truly empty.

How do you show empty strings in Python?

String len() The len() function returns the length of a string, the number of chars in it. It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0.

Is empty string true in Python?

Practical Data Science using PythonEmpty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.

How do you convert an empty string to a string in Python?

Method #2 : Using str() Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which evaluates to empty string is returned.


1 Answers

'' is the empty string, same as "". The empty string is a substring of every other string.

When a and b are strings, the expression a in b checks that a is a substring of b. That is, the sequence of characters of a must exist in b; there must be an index i such that b[i:i+len(a)] == a. If a is empty, then any index i satisfies this condition.

This does not mean that when you iterate over b, you will get a. Unlike other sequences, while every element produced by for a in b satisfies a in b, a in b does not imply that a will be produced by iterating over b.

So '' in x and "" in x returns True for any string x:

>>> '' in 'spam'
True
>>> "" in 'spam'
True
>>> "" in ''
True
>>> '' in ""
True
>>> '' in ''
True
>>> '' in ' ' 
True
>>> "" in " "
True
like image 54
Rushy Panchal Avatar answered Sep 29 '22 11:09

Rushy Panchal