简答题
偏难
#15319
查找与替换 用Python编写一个字符串查找替换的程序,功能如下:输入原文字符串(text)、要查找的字符串(key)以及要替换的字符串(rs),程序对原文进行…
查找与替换
用Python编写一个字符串查找替换的程序,功能如下:输入原文字符串(text)、要查找的字符串(key)以及要替换的字符串(rs),程序对原文进行检索,若找到要查找的字符串,则进行替换并统计替换次数,最后输出替换后的结果;若找不到,则输出“要查找的内容不存在”。例如输入原文“In our beautiful campus, suqirrels, which like freedom can be seen everywhere”、查找内容“suqirrels”、替换内容“egret”。输出“In our beautiful campus,egret,which like freedom can be seen everywhere"。程序如下,请完善空白处的代码。
text=input("输入原文字符串:")
key=input("输入要查找的字符串:")
rs=input("输入替换字符串:")
result=""
count=0
i=0
n=len(text)
while i<n-len(key)+1:
s=text[ ① ]
if key==s:
result+= ②
count+=1
i+=len(key)
else:
result+=text[i]
i+=1
③
if ④
print("替换的次数:",count)
print("替换后的结果:",result)
else:
print("要查找的内容不存在")
答案与解析
正确答案:<pre class="brush:python;toolbar:false">text=input("输入原文字符串:")
key=input("输入要查找的字符串:")
rs=input("输入替换字符串:")
result=""
count=0
i=0
n=len(text)
while i<n-len(key)+1:
s=text[i:i+len(key) ]
if key==s:
result+=rs
count+=1
i+=len(key)
else:
result+=text[i]
i+=1
result+=text[i:]
if count>0:
print("替换的次数:",count)
print("替换后的结果:",result)
else:
print("要查找的内容不存在")</pre>
解析
评分标准:
(1)i:i+len(key) (或等效答案);(2分)
(2)rs(或等效答案);(2分)
(3)result+=text[i:] (或等效答案);(3分)
(4)count>0: 写成“count>0”(或等效答案)。(3分)(漏写了冒号给2分)