Python Forum
Why does 'nothing' count as a string?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does 'nothing' count as a string?
#1
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.
Output:
"" IS in the allowable letters.
If you add print (ord (test_string)) in between the fourth and fifth line, the error will say :
Output:
TypeError: ord() expected a character, but string of length 0 found
So… my question is, why does python think that nothing or a zero length string IS in ‘abcdefg’?
Reply
#2
(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 ''
True
The 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
Reply
#3
You can also write this
if test_string and test_string in allowable_letters :
    ...
Reply
#4
Thank you both Smile
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Row Count and coloumn count Yegor123 4 1,514 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  String Count Kristenl2784 1 1,760 Jul-23-2020, 02:10 AM
Last Post: millpond
  Beginner at Python. Trying to count certain integer from random string of code kiaspelleditwrong 3 2,560 Oct-14-2019, 10:40 AM
Last Post: perfringo
  How to Find & Count String Patterns Between two Markers in a HTML file ahmedwaqas92 3 3,142 Aug-19-2019, 10:12 AM
Last Post: ahmedwaqas92
  count string occurrences of 2nd file in lines of first showkat 1 2,475 Mar-01-2018, 11:25 AM
Last Post: showkat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020