【发布时间】:2020-05-23 11:07:02
【问题描述】:
我正在尝试根据用户输入不断替换字符串中的子字符串,但我的 string.replace 语法似乎用用户输入的子字符串替换了整个字符串。这是代码:
import re
secret_word = 'COMPUTER'
clue = len(secret_word) * '-' # this step gives the user the nos of characters in secret_word
user_guess = input("Type a single letter here, then press enter: ")
user_guess = user_guess.upper()
if user_guess in secret_word:
index = [match.start() for match in re.finditer(user_guess, secret_word)] # this finds the index of the user guess in secret_word
print(index)
for i in index:
clue = clue.replace(clue[i], user_guess)
print("The word now looks like this: "+ clue)
我不确定为什么它不只替换子字符串。
【问题讨论】:
-
你能给我们展示一个示例输入和预期输出吗?