L.Davis
L.Davis

Reputation: 41

Hangman-Game: Words have unwanted character at the end

This is a part of my code for a hangman game. it is used for all four difficulties, but when it is used on my "insane" difficulty (which uses words from a word file) it adds an extra symbol to the end of the word meaning you can't win the game. it does this for every word in the .txt file. This code works when using an array in the python window.

def insane():
    global score  
    print ("This words may contain an apostrophe. \nStart guessing...")

    time.sleep(0.5)

    word = random.choice(words).lower()
    print (word)
    guesses = ''
    fails = 0
    while fails >= 0 and fails < 10:  #try to fix this         
        failed = 0                
        for char in word:      
            if char in guesses:    
                print (char,)    

            else:
                print ("_"),     
                failed += 1    
        if failed == 0:        
            print ("\nYou won, WELL DONE!")
            score = score + 1
            print ("your score is,", score)
            difficultyINSANE()

        guess = input("\nGuess a letter:").lower()
        guesses += guess   
        if guess not in word:  
            fails += 1        
            print ("\nWrong")

            if fails == 1:
                print ("You have", + fails, "fail....WATCH OUT!" )
            elif fails >= 2 and fails < 10:
                print ("You have", + fails, "fails....WATCH OUT!" ) 
            if fails == 10:           
                print ("You Loose\n")
                print ("your score is, ", score)
                print ("the word was,", word)
                score = 0 
                difficultyINSANE()

Edit:

this is how i read the words

INSANEWORDS = open("create.txt","r+") 
words = [] 
for item in INSANEWORDS:
   words.append(item) 

Upvotes: 2

Views: 159

Answers (2)

JDurstberger
JDurstberger

Reputation: 4255

You have a \n at the end of every word. You should strip the word of the \n before adding it:

INSANEWORDS = open("create.txt", "r+")
words = []
for item in INSANEWORDS:
    words.append(item.strip('\n'))

Before:

enter image description here

After:

enter image description here

Upvotes: 1

ddalu5
ddalu5

Reputation: 401

If my guess is correct when you are reading a line from your text file you also reading the new line character \n at the end of the word, which you can remove using:

word = word.strip('\n')

Upvotes: 0

Related Questions