Normally this would return False, however if I add white space to the 'Chevrolet ’ in the list, and add .rstrip() after that .title() it would return true. Should it be like this? Are there other ways to search for items in the list if they contain white space and/or title cases?
The .rstrip() after that .title() works on car_of_choice_0, which has no space, so it is a no-op. The ‘Chevrolet ’ literal in the list would have a space, though. Hence they are not the same so the value doesn’t occur in the list.
TLDR: Yes, this works as described.
To search a list with ‘messy’ data you first need to ‘clean’ it. Alternatively, and more advanced, you could search with e.g. regex.
Here is a little play on your current test script. If you want to test if the string that you entered is within any of the options regardless off empty spaces, you may add a for loop as shown in the following test script. We initially set the result flag to False as the default value. If, after running the script, there is a match, we change its value to True and break from the loop.
cars = ['subaru', 'bmw', 'honda', 'cintroen','toyota','chevrolet ']
car_of_choice_0 = 'chevrolet'
result = 'False'
for i in cars:
if car_of_choice_0 in i:
result = 'True'
break
print(result)
If you runt the script, you will get a True result.
When searching through a list I usually change all list items to lowercase, and change the string I’m search for to lowercase. I also clean up each item in the list to remove white space on the left and right side of each string.
Also if you use regex and re.search(), and that re.search() is inside a long loop, it slows down the program considerably. (My loops can run through 2000-500,000 records.) And that’s why I use if something in [] more often, like to break at a line when debugging.
testpart='ABC123'
if testpart.lower() in ['ddd444', 'abc123', 'aaa555']:
z = 0 # Set breakpoint here or use below
breakpoint() # This is an always-on breakpoint.