【发布时间】: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