[英]replacing a substring in a string: Python
我正在嘗試根據用戶輸入不斷替換字符串中的子字符串,但我的 string.replace 語法似乎用用戶輸入的 substring 替換了整個字符串。 這是代碼:
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)
我不確定為什么它不只替換子字符串。
原因是clue = clue.replace(clue[i], user_guess)
。 clue[i]
開頭總是等於'*'
,因此替換 function 將用 user_guess 替換所有字符。
一種解決方案是將clue
更改為列表而不是字符串clue = len(secret_word) * ['-']
並將替換操作替換為clue[i] = user_guess
不要忘記更新打印操作:在 print( "".join(clue)
print("The word now looks like this: "+ clue)
clue
在 python 中,當您使用 str.replace str.replace(x, substitution)
時,它會將每次出現的x
substituion
為字符串str
中的替換。
在開始時,變量clue
包含--------
字符串,因此您的替換方法被稱為clue.replace('-', U)
考慮到,用戶提供了輸入u
,這反過來替換了每次出現-
即UUUUUUUU
的整個字符串clue
。
實現此目的的一種方法是將您的代碼更改為以下內容:
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[:i] + user_guess + clue[i:]
print("The word now looks like this: "+ clue)
secret_word = 'COMPUTER'
clue = str(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 = user_guess.find(user_guess) # this finds the index of the user guess in secret_word
clue = clue[:index] + user_guess + clue[index+1:]
print("The word now looks like this: " + clue)
試試這個你不需要正則表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.