简体   繁体   中英

How do I test a string variable to see if it is in a list of strings

I am using python and coding a game where words have to start with the last letter of the word before, and I am trying to find a method to make my code look at a list of strings that have already been entered and choose a new word that is not one of those from a separate text file I already have set up. This is what I have so far but I am unsure what to do next. (Note: all of my checks for word viability other than if the word has been said previously work.)

def ai_choice(last: List[str]):
previous_word = last[-1]
f = open('english3.txt', 'r')
for line in f:
    if line.lower().strip()[0] == previous_word[len(previous_word) - 1] and line != :
        return True
    else:
        return False

It should look like this

last_letter = None 
Words_used = []
word = input("your word >>")

if word not in Words_used:
    Words_used.append(word)
else :
    print("word is used")
    
last_letter = word[-1]

print("next word should start with >> ",last_letter)

now you can use a file instead of Words_used and make a function of the above snippet or run in a loop

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