You can use the count() method to count the number of occurrence of a letter.
secret = "Apple"
secret.count('p')
gives
2
문제
I'm using pyscripter to create a hangman game. I have managed to get everything to work except one thing. This is that once i have found the correct word the script needs to match this to the secret word. This would usually be easy but the way i have done it leaves gaps in the string. What i want to do is using the number of letters in the secret word; when i enter a letter it looks for that letter and adds how many times the letter appears in the secret word. i.e. the letter "P" in APPLE appears 2 times, therefore adding 2 to a separate string. if the word was "APPLE" the program would be looking for 5 correct letters. This way i can make an "if" statement and end the game once the numbers of correct letters guessed matches the length of the secret word. This is the program i am using : http://i1.ytimg.com/vi/1HZ38RzykuE/maxresdefault.jpg
Does this make sense, I've been pondering on it for a while so it may be jumbled. Thank you if your able to help.
This is the code i am using: (blanktotal is the length of the secret word)
else:
if letter in secretword:
letterscorrect = letterscorrect + 1
os.system("cls")
if letter not in guessedletters:
os.system("cls")
for x in range(0, len(secretword)):
if letter == secretword[x]:
for x in range(len(secretword)):
if secretword[x] in letter:
hiddenletter = hiddenletter[:x] + secretword[x] + hiddenletter[x+1:]
guessedletters.append(letter)
else:
print("")
else:
print("")
for letter in hiddenletter:
print(letter, end=' ')
print("")
if letterscorrect == blanktotal:
os.system("cls")
print("")
print("congratulations you have won!!!!")
print("You are now the master of HANGMAN!!!!!")
print("")
해결책
You can use the count() method to count the number of occurrence of a letter.
secret = "Apple"
secret.count('p')
gives
2
다른 팁
I think you're just looking for the count
method:
>>> s = 'APPLE'
>>> s.count('P')
2