Imran
Imran

Reputation: 63

How to mask with '_' a part of a string in python

It's for our class hangman game project, it's divided in many steps and the fourth one is : Objective :

  1. As in the previous stage, you should use the following word list: 'python', 'java', 'kotlin', 'javascript'

  2. 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

Answers (3)

en3rgizer
en3rgizer

Reputation: 36

Try this code:

word = "Java"
hiddenWord = word[:3]
hiddenWord += '-' * (len(word)-3)

Upvotes: 1

JNevill
JNevill

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

Andrej Kesely
Andrej Kesely

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

Related Questions