Why am I getting an additional "*" on some lines of my python app?

RobbYoung

I've been asked for my A Level computing to create a text based hangman game. For some reason, when the "guessword" is displayed, it contains an additional character at the end, which cannot be solved, and therefore makes the game unwinnable. This only happens on a few circumstances, not every word in the list has this additional character.

Here is the python code:

import random

class Hangman():

def Playing(self):

    category = raw_input("Please select a category from; EuroCapitals; PremTeams; FruitAndVeg")
    again = True
    while again:

        guessword = open(category + ".txt", "r").readlines()[random.randint(0,9)]
        board = "*" * (len(guessword) - 1)
        alreadySaid = set()
        mistakes = 7

        print(" ".join(board))

        guessed = False
        while not guessed and mistakes > 0:

            whatplayersaid = raw_input("Guess a letter: ")

            if whatplayersaid in guessword:
                alreadySaid.add(whatplayersaid)
                board = "".join([char if char in alreadySaid else "*" for char in guessword])
                if board == guessword:
                    guessed = True
            else:
                mistakes -= 1
                print("Nope.", mistakes, "mistakes left.")

            print(" ".join(board))

        again = (input("Again [y/n]: ").lower() == 'y')


Hangman().Playing()

And the list of words in "EuroCapitals.txt" is as follows:

london
paris
madrid
berlin
moscow
rome
amsterdam
bern
zagreb
stockholm

Any help would be greatly appreciated.

FatalError

Most likely it's a \n character (or maybe some extra whitespace?) from the file -- readlines() will preserve them if they are in the file. So, you want to .rstrip() your guessword, e.g.:

    guessword = open(category + ".txt", "r").readlines()[random.randint(0,9)].rstrip()

As an aside, creating an anonymous file object like this generally isn't a good idea, because it won't be closed right away. You're better off using a with statement:

    with open(category + ".txt", "r") as f:
        guessword = f.readlines()[random.randint(0,9)].rstrip()

and you could further refine it with

    with open(category + ".txt", "r") as f:
        guessword = random.choice(f.readlines()).rstrip()

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Why am I getting these errors in my Server/Client Chatroom program?

분류에서Dev

I am trying to perform the Euler method in python but I am getting a 'type error', why?

분류에서Dev

Why am I getting undefined for my variable in the controller but it displays correctly in the HTML page with data binding

분류에서Dev

Why am I getting a black line around my 32-bit context in Cocos2D?

분류에서Dev

Why Am I Getting an IllegalStateException While Adding Bcrypt to my Spring-Security.XML file?

분류에서Dev

Why am I getting this syntax logic error?

분류에서Dev

Why am I getting unexpected string error?

분류에서Dev

Why am I getting the wrong MANIFEST?

분류에서Dev

Why am I not getting any accelerometer update?

분류에서Dev

Why Am I getting this Input Error?

분류에서Dev

Why am I getting a The installer was interrupted before xxx could be installed error when installing my ASP.Net Web application with installer?

분류에서Dev

Can I get data from my MSSql server and upload it to app engine via some python scripts?

분류에서Dev

Why am I getting (NameError: global name 'secondRoom' is not defined)?

분류에서Dev

Why am I getting java.util.ConcurrentModificationException?

분류에서Dev

Does anyone know why I am not getting any results with this query?

분류에서Dev

Why am I getting this error: "error: { expected" in JCreator?

분류에서Dev

Why am I getting EXC_BAD_ACCESS error

분류에서Dev

Why am I getting an error while using group by with a left join?

분류에서Dev

Why am I getting a segfault on string tokenizer function?

분류에서Dev

Why am I getting an error when creating Spring Beans in JHipster?

분류에서Dev

Why am I getting garbage value from a function call?

분류에서Dev

Why am I getting "invalid max count" from grep in an alias?

분류에서Dev

Why am I getting no output from this short Perl script?

분류에서Dev

In my iPhone app,i am trying to implement a UISearchBar in Tableview

분류에서Dev

Why is my VBA/SQL query say I am missing an operator?

분류에서Dev

Why am I not being able to connect to my database?

분류에서Dev

My files are writeable, why am I seeing filesize() and fread() errors?

분류에서Dev

I am Trying to run a titanium project in ios simulator but getting some node error

분류에서Dev

Can I have an array that does not have a limit because I am getting my input by scanner?

Related 관련 기사

  1. 1

    Why am I getting these errors in my Server/Client Chatroom program?

  2. 2

    I am trying to perform the Euler method in python but I am getting a 'type error', why?

  3. 3

    Why am I getting undefined for my variable in the controller but it displays correctly in the HTML page with data binding

  4. 4

    Why am I getting a black line around my 32-bit context in Cocos2D?

  5. 5

    Why Am I Getting an IllegalStateException While Adding Bcrypt to my Spring-Security.XML file?

  6. 6

    Why am I getting this syntax logic error?

  7. 7

    Why am I getting unexpected string error?

  8. 8

    Why am I getting the wrong MANIFEST?

  9. 9

    Why am I not getting any accelerometer update?

  10. 10

    Why Am I getting this Input Error?

  11. 11

    Why am I getting a The installer was interrupted before xxx could be installed error when installing my ASP.Net Web application with installer?

  12. 12

    Can I get data from my MSSql server and upload it to app engine via some python scripts?

  13. 13

    Why am I getting (NameError: global name 'secondRoom' is not defined)?

  14. 14

    Why am I getting java.util.ConcurrentModificationException?

  15. 15

    Does anyone know why I am not getting any results with this query?

  16. 16

    Why am I getting this error: "error: { expected" in JCreator?

  17. 17

    Why am I getting EXC_BAD_ACCESS error

  18. 18

    Why am I getting an error while using group by with a left join?

  19. 19

    Why am I getting a segfault on string tokenizer function?

  20. 20

    Why am I getting an error when creating Spring Beans in JHipster?

  21. 21

    Why am I getting garbage value from a function call?

  22. 22

    Why am I getting "invalid max count" from grep in an alias?

  23. 23

    Why am I getting no output from this short Perl script?

  24. 24

    In my iPhone app,i am trying to implement a UISearchBar in Tableview

  25. 25

    Why is my VBA/SQL query say I am missing an operator?

  26. 26

    Why am I not being able to connect to my database?

  27. 27

    My files are writeable, why am I seeing filesize() and fread() errors?

  28. 28

    I am Trying to run a titanium project in ios simulator but getting some node error

  29. 29

    Can I have an array that does not have a limit because I am getting my input by scanner?

뜨겁다태그

보관