简答题
偏难
#16485
字符串替换 小明在信息科技课上学习了word的基本操作后,了解到word中替换功能可以将文档中指定内容一次性全部替换成其他文本,于是试着在Python中编程实现…
字符串替换
小明在信息科技课上学习了word的基本操作后,了解到word中替换功能可以将文档中指定内容一次性全部替换成其他文本,于是试着在Python中编程实现相关功能,功能描述如下:
在字符串s中,查找指定的字符c1(可以是单个字符,也可以是多个字符的组合)并替换成其他字符c2。例如:输入s的值为:"A person in need is a person indeed!",输入c1的值为:person,输入c2的值为"friend",则显示的结果是"A friend in need is a friend indeed!"。实现上述功能的python代码如下:运行界面如图所示:
请在划线处填入适当的代码.
s=input("请输入文本字符串:")
c1=input("请输入要替换的字符:")
c2=input("请输入要替换成的新字符:")
n=len(c1)
s1=""
i=0
while i<len(s):
c= ①
if c==c1:
s1=s1+c2
i= ②
else:
s1= ③
④
print("替换后的结果:",s1)
答案与解析
正确答案:<pre class="brush:python;toolbar:false">s = input("请输入文本字符串:")
c1 = input("请输入要替换的字符:")
c2 = input("请输入要替换成的新字符:")
n = len(c1)
s1 = ""
i = 0
while i < len(s):
c =s[i:i+n]
if c == c1:
s1 = s1+c2
i = i+n
else:
s1 =s1+s[i]
i=i+1
print("替换后的结果:",s1)</pre>
解析
评分标准:
(1)s[i:i+n] 或等效答案;(3分)
(2)i+n 或等效答案;(3分)
(3)s1+s[i] 或等效答案;(2分)
(4)i=i+1 或等效答案。(2分)