简体   繁体   中英

How to recode line so an exact sentence must be in the list for it to match

x = ["Cookie flavored water is yummy 6", "Coding complicated 16", "Help 7"]

for i in x:
    if "flavored" in x:
        print ("Yes")
    else:
        print ("No")

I want the exact string "Cookie flavored water is yummy" to be in the list for it to be acceptable but I don't want the 6 part included. I'm completely befuddled on how to accomplish this. Also the objective might change from the first element to a different element.

Well if the string is always the one you specified you could do this:

yourString = "Cookie flavored water is yummy"
for item in x:
    if yourString in item:
        print 'Yes'
    else:
        print 'No'

This check each list item for the specified string. In your example "Cookie flavored water is yummy 6" contains the substring "Cookie flavored water is yummy". So the script will print 'Yes'

you're iterating on x with i but you check if string belongs to the list, not the element, which is always false.

to check if an element of x contains "Cookie flavored water is yummy"

x = ["Cookie flavored water is yummy 6", "Coding complicated 16", "Help 7"]

for i in x:
    print ("Yes" if "Cookie flavored water is yummy" in i else "No")

on the other hand, for exact string match simply use in without a loop, the loop being made on x by the in operator:

print ("Yes" if "Cookie flavored water is yummy" in x else "No")

If you need exact string match on a great number of elements, consider putting your elements in a set instead because lookup time is much smaller (hashing involved). The code remains the same apart from that.

What do you mean by "acceptable?" Additionally, when you say you don't want the number at the end of the items in the list to be included, do you mean for your comparison? I agree with the other answers, and if you happen to want to remove the numbers from the list:

x = [' '.join(i.split(' ')[:-1]) for i in x]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM