简体   繁体   中英

Checking if a word is in a list in Python

I am beginner in learning Python and have been practicing quit a bit however I have been having difficulties with a certain code I would like to write.

Essentially, I want to write a code which would analyse the word(s) in each list to check whether the word deer is indeed in the list mammals and print a certain message.

Here was my attempt:

myMammals = ['cow', 'cat', 'pig', 'man', 'woman']
ASCIIcodes = []
ASCII = x
for mammal in myMammals:
    for letter in mammal:
        x = ord(letter)
        ASCIIcodes.append(x)
print ASCIIcodes

animal = ['deer']
ASCIIcodes2 = []
ASCIIvalue = x
for word in animal:
    for letter in word:
        x = ord(letter)
        ASCIIcodes2.append(x)
print ASCIIcodes2

The code above, when run, returns:

[99, 111, 119, 99, 97, 116, 112, 105, 103, 109, 97, 110, 119, 111, 109, 97, 110]
[100, 101, 101, 114]

Reason why I wrote the code above was because I thought I could somehow create a list of the ascii codes of each character and then use those lists to do my comparison of the ascii codes as to check whether deer is indeed in the list of mammals

I would suggest a function along the following:

def check(word, list):
    if word in list:
        print("The word is in the list!")
    else:
        print("The word is not in the list!")

This is assuming you're using Python 3.x, if you're using Python 2, then there shouldn't be parenthesis in your print statements

Hope this helps!

Welcome to Python! This sort of thing is really elementary here. What you need is

print('deer' in myMammals)
>> True
wordchecker = input("please enter your sentence ->")
wordfinder = input("please enter the word you want to find in your sentence -> ")
if wordfinder in wordchecker:
    print(f"_{wordchecker}_ has _{wordfinder}_ in it")
else:
    print(f"_{wordchecker}_ doesn't have _{wordfinder}_ in it")

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