Reputation: 63
It's for our class hangman game project, it's divided in many steps and the fourth one is : Objective :
As in the previous stage, you should use the following word list: 'python', 'java', 'kotlin', 'javascript'
Once the computer has chosen a word from the list, show its first 3 letters. Hidden letters should be replaced with hyphens ("-").
Examples:
Example 1
H A N G M A N Guess the word jav-: > java
You survived!
Example 2
H A N G M A N Guess the word pyt---: > pythia
You lost!
My problem
Here is my hint function witch is suppose to mask the characters after the third first one :
def hint(word: str) -> str:
print(word)
print(len(word))
# for the debugging the replace function seem to replace an identified 'string' by another
replaced = word.replace(word[3:], "-" * (len(word)-3))
print(replaced)
return replaced
It works with the other words (python, kotlin...) but when the word to guess is 'Java', it gives me as output "J-v-"
Upvotes: 2
Views: 732
Reputation: 36
Try this code:
word = "Java"
hiddenWord = word[:3]
hiddenWord += '-' * (len(word)-3)
Upvotes: 1
Reputation: 50200
word[3:]
returns an a
.
(len(word)-3)
returns 1
.
So you end up with each a
being replaced with a hyphen:
"Java".replace('a', '-')`
>>>J-v-
Instead avoid replace()
. You can consider:
replaced = word[:3] + '-' * len(word[3:])
Upvotes: 3
Reputation: 195543
As stated in the comments, you don't have to use str.replace
, just construct new string:
words = ["python", "java", "kotlin", "javascript"]
def hint(word):
return word[:3] + "-" * (len(word) - 3)
for w in words:
print(w, hint(w))
Prints:
python pyt---
java jav-
kotlin kot---
javascript jav-------
Upvotes: 2