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?
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.
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.
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.
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.
''
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With