这个字符串相等比较有什么问题? (蟒蛇)

时间:2014-12-15 01:33:07

标签: python string comparison

我的代码适用于简单的刽子手类型游戏,用户应该逐个字母地猜测列表中的随机单词或猜测整个单词。用户猜测整个单词的比较不会执行。我将下面的代码中的一个可能的随机单词硬编码为一个例子:

guess = "----"
letterCount = 8
letter = ""

x = 0
while letterCount > 0:
    temp1 = "word"
    letter = input("Guess a letter in the word or attempt to guess the whole word: ")
    if (len(letter) > 1):
        print ("this is the test word: word, this is letter:" + letter)
        if letter == "word":
            print ("You win!!!")
            letterCount = 0
    else:
        x = temp1.find(letter)
        while x != -1:
            x = temp1.find(letter)
            temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
            guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
        print (("Your guess is now: " + guess))
    letterCount = letterCount - 1
    x = 0

如果我猜“单词”,它告诉我,我猜单词,它指出我想我应该这个词,但if语句应该告诉我,我永远不会执行。我正确比较这些字符串还是其他问题?

1 个答案:

答案 0 :(得分:1)

>>> while letterCount > 0:
...     temp1 = "word"
...     letter = input("Guess a letter in the word or attempt to guess the whole word: ")
...     if (len(letter) > 1):
...         print ("this is the test word: word, this is letter:" + letter)
...         if letter == "word":
...             print ("You win!!!")
...             letterCount = 0
...     else:
...         x = temp1.find(letter)
...         while x != -1:
...             x = temp1.find(letter)
...             temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
...             guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
...         print (("Your guess is now: " + guess))
...     letterCount = letterCount - 1
...     x = 0
...
Guess a letter in the word or attempt to guess the whole word: "word"
this is the test word: word, this is letter:word
You win!!!
>>>

您需要将输入转换为字符串,以便字符串比较测试起作用。