【问题标题】:replacing a substring in a string: Python替换字符串中的子字符串:Python
【发布时间】: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)

我不确定为什么它不只替换子字符串。

【问题讨论】:

  • 你能给我们展示一个示例输入和预期输出吗?

标签: python string substring


【解决方案1】:

原因是clue = clue.replace(clue[i], user_guess) 行。 clue[i] 在开头总是等于'*',所以替换函数将用 user_guess 替换所有字符。

一种解决方案是将clue 更改为列表而不是字符串clue = len(secret_word) * ['-'] 并将替换操作替换为clue[i] = user_guess

不要忘记更新打印操作:clue 变成 "".join(clue) in print("The word now looks like this: "+ clue)

【讨论】:

    【解决方案2】:
    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)
    

    试试这个,你不需要正则表达式。

    【讨论】:

    • 感谢 Sachin 的回复。我仍然面临一个问题。此解决方案仅在被替换的子字符串在字符串中仅出现一次时才有效。如何为它编写代码来更新字符串中特定子字符串的所有实例。例如,在您的解决方案中,如果 secret_word 是“HAPPY”,当用户输入“P”时,只有第一次出现的 P 会在变量“clue”中更新。
    • @O.Edward 看来你已经接受了答案你还想让我再解决吗?
    【解决方案3】:

    在 python 中,当您使用str.replace(x, substitution) 时,它会将字符串str 中出现的x 替换为substituion

    在变量clue的开头包含--------字符串,因此您的替换方法被称为clue.replace('-', U)考虑到,用户提供了输入u,这反过来又替换了@987654329的每一次出现@ 即整个字符串 clueUUUUUUUU

    实现此目的的一种方法是将您的代码更改为以下内容:

    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)
    

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 2016-09-17
      • 2021-06-13
      • 2012-04-03
      • 2013-07-23
      • 2016-12-24
      相关资源
      最近更新 更多