Your code problem is in the repeat block. You are using the string size char
- which theoretically must contain only one character - in the function range()
as a stop point, when you should be using the string size word
.
for i in range(0, len(word) - 1):
...
Also, another problem of your code, still on the same line, is the use of subtraction -1
at the stop point of the function. You must not subtract the value of the stop
, because the function defines this value as its "definitive" limit. See the example below:
list(range(5)) # [0, 1, 2, 3, 4]
list(range(5 - 1)) # [0, 1, 2, 3]
That said, your code should look like this:
def char_check(char, word):
newWord_list = []
newWord_ = ''
# O valor padrão de "start" é zero. Sendo assim, não precisa especificá-lo.
for i in range(len(word)):
if char == word[i]:
newWord_list.append(char)
else:
newWord_list.append('_')
newWord_ = ''.join(newWord_list)
return newWord_
In addition, you can further improve your role without having to create a new list. To do this, traverse each character of your string through the loop for
and check that the letter is the same as char
. If yes, add it to the new string. If not, add the string "_"
. See how it would look:
def char_check(char, word):
new_word = ""
for letter in word:
if char == letter: new_word += char
else: new_word += "_"
return new_word
It is also possible to do all this in just one line, using comprehensilist on, as follows:
def char_check(char, word):
return "".join([char if char == letter else "_" for letter in word])
char
is only supposed to be a letter, right? If yes, the function is not entering the loop sincelen(char)-1
=0– Lucas