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}')

5

u/socal_nerdtastic Sep 26 '24

The cool modern way is with a walrus:

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

1

u/bkabartsy Sep 26 '24

very cool. definitely more pythonic than my_string = ' ' or my_string = 'x'

1

u/assembly_wizard Sep 26 '24

The walrus operator won't always fit so nicely into your problem, so here's how you would write this using a do-while loop:

my_string = None
while True:
    my_string = input()
    if my_string in 'abc':
        break
    print(f'not printed: {my_string}')

(in this specific case the walrus is better, but this while true pattern is still useful sometimes)

2

u/Temporary_Pie2733 Sep 26 '24

No need to initialize my_string before the loop begins; the first in-loop assignment is guaranteed to occur.