![]() |
Why does 'nothing' count as a string? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why does 'nothing' count as a string? (/thread-35493.html) |
Why does 'nothing' count as a string? - BashBedlam - Nov-09-2021 allowable_letters = 'abcdefg' while True : test_string = input ('\nEnter a letter or number :') if test_string in allowable_letters : print (f' "{test_string}" IS in the allowable letters.') else : print (f' "{test_string}" is NOT in the allowable letters.')In the above code, entering a letter or number or even a string like ‘abc’ or ‘BashBedlam’ has the correct and expected result. However, if you press enter without typing anything else in, it will tell you that what your input IS in the allowable letters. If you add print (ord (test_string)) in between the fourth and fifth line, the error will say : So… my question is, why does python think that nothing or a zero length string IS in ‘abcdefg’?
RE: Why does 'nothing' count as a string? - snippsat - Nov-09-2021 (Nov-09-2021, 04:21 PM)BashBedlam Wrote: So… my question is, why does python think that nothing or a zero length string IS in ‘abcdefg’?A empty string is a substring of every string. >>> '' in 'hello' True >>> '' in 'h' True >>> '' in '' TrueThe easiest solution for your code is to add list('abcdefg') then do not need to test for empty string.>>> 'h' in list('hello') True >>> '' in list('hello') False RE: Why does 'nothing' count as a string? - Gribouillis - Nov-09-2021 You can also write this if test_string and test_string in allowable_letters : ... RE: Why does 'nothing' count as a string? - BashBedlam - Nov-10-2021 Thank you both ![]() |