r/learnpython • • Sep 26 '24

Empty strings - am i tripping?

>>> '' in 'abc'
True

can someone explain? (python 3.12.6)

1 Upvotes

27 comments sorted by

View all comments

53

u/Binary101010 Sep 26 '24

Directly from the Python docs:

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

https://docs.python.org/3/reference/expressions.html#membership-test-operations

0

u/bkabartsy Sep 26 '24

TIL, thank you.

what is the pythonic way of initializing an empty string and writing a while loop to populate that string with user input?

my_string = '' # wrong
while my_string not in 'abc':  
    my_string = input()  
    print(f'not printed: {my_string}')

0

u/jso__ Sep 26 '24

Try it with a list:

In [1]: "" in ["a", "b", "c"]
Out[1]: False

4

u/barry_z Sep 26 '24

This may still not be what they want - 'ab' in 'abc' would evaluate to True while 'ab' in ['a', 'b', 'c'] would evaluate to False.

-5

u/LuciferianInk Sep 26 '24

Penny whispers, "What is the difference between ```"