【问题标题】:How to replace multiple letters in a string using an index如何使用索引替换字符串中的多个字母
【发布时间】:2021-03-10 19:01:19
【问题描述】:

我正在使用一个名为 introcs 的模块来替换指定字母的第一次出现。在您要求它替换两个字母之前,它运行良好。关于如何改进此代码的任何建议?它不适用于最后两个示例(见下文)。

def replace_first(word,a,b):
    """
    Returns: a copy of word with the FIRST instance of a replaced by b
    
    Example1: replace_first('crane','a','o') returns 'crone'
    Example2: replace_first('poll','l','o') returns 'pool'
    Example3: replace_first('crane','cr','b') returns 'bane'
    Example4: replace_first('heebee','ee','y') returns 'hybee'
    
    Parameter word: The string to copy and replace
    Precondition: word is a string
    
    Parameter a: The substring to find in word
    Precondition: a is a valid substring of word
    
    Parameter b: The substring to use in place of a
    Precondition: b is a string
    """
    
    pos = introcs.index_str(word,a)
    #print(pos)
    before = word[:pos]
    after  = word[pos+1:]
    #print(before)
    #after  = word[pos+1:]
    #print(after)
    result = before+b+after
    #print(result)
    return result 

【问题讨论】:

  • 为什么不只是"crane".replace("a", "o", 1)?其中第三个参数,即1 是替换计数
  • 你好。看起来正则表达式在这里可能会有所帮助。看看这个看看它是否有帮助 - stackoverflow.com/a/3951684/4162268.
  • 用你自己的话说,当你做after = word[pos+1:]时,1是从哪里来的?您说当您尝试替换多个字母时,它无法正常工作。你能找出失败的模式吗?你能想出一种方法来改变这行代码,考虑到有多少个字母被替换了吗? (提示:你能想出一种方法来检查有多少字母被替换了吗?)
  • 这能回答你的问题吗? Replace first occurrence of string in Python

标签: python python-3.x


【解决方案1】:

string 包有替换功能。您可以编写一个替换出现次数的函数。例如:

def replaced(word, a, b, replacement_count):
    return word.replace(a, b, replacement_count)

【讨论】:

    【解决方案2】:

    您必须更改after 的定义。 将其更改为:

    after = word[pos+len(a):]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 2020-07-26
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多