A17921. 查找与替换用Python编写一个字符串查找替换的程序,功能如下:输入原文字符串(text)、要查找的字符串(key)以及要替换的字符串(rs),程序对原文进行检索,若找到要查找的字符串,则进行替换并统计替换次数,最后输出替换后的结果;若找不到,则输出“要查找的内容不存在”。例如输入原文“In our beautiful campus, suqirrels, which like freedom …
填空题
困难
知识点
题目描述
查找与替换
用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("要查找的内容不存在")参考答案
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("要查找的内容不存在")
上一题
下一题