万卷网 > 题目详情
题型:编程题

字符串替换

小明在信息科技课上学习了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)

更新时间:2025-04-16 20:27:18 |
【知识点】 电子学会Python五级

相似题推荐

单选题

埃氏筛中将内层循环从j = i*i 开始而不是j = 2*i 的主要原因是()。

def eratosthenes_sieve_for(n):
    if n < 2:
        return []
    is_composite = [False] * (n + 1)
    primes = []

    for i in range(2, n + 1):
        if is_composite[i]:
            continue
        primes.append(i)

        # 用for循环模拟C++的 j = i*i; j <=n; j +=i
        for j in range(i * i, n + 1, i):
            is_composite[j] = True

    return primes


A.

因为2*i 一定不是合数

B.

i*i 一定是质数

C.

小于i*i 的i 的倍数已被更小质因子筛过

D.

这样可以把时间复杂度降为O(n)

2026-09-14
判断题

快速排序只要每次都选取中间元素作为枢轴,就一定是稳定排序。

A.正确 B.错误
2026-09-14
单选题

对如下代码实现的欧几里得算法(辗转相除法),调用gcd(48 , 18) 得到的调用序列为()。

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)


A.gcd(48 ,18) -> gcd(18 ,12) -> gcd(12 ,6) -> gcd(6 ,0) B.gcd(48 ,18) -> gcd(30 ,18) -> gcd(12 ,18)
C.gcd(48 ,18) -> gcd(18 ,30) -> gcd(30 ,6) D.gcd(48 ,18) -> gcd(12 ,18) -> gcd(6 ,12)
2026-09-14
单选题

下面代码用分治求“最大连续子段和”,其时间复杂度为()。

import sys
def solve(a , l , r):
    if l == r:
        return a [l]
    mid = l + (r - l) // 2
    left = solve(a , l , mid)
    right = solve(a , mid + 1 , r)
    sum_val = 0
    lmax = -sys .maxsize - 1
    for i in range(mid , l - 1 , -1):
        sum_val += a [i]
        lmax = max (lmax , sum_val)
    sum_val = 0
    rmax = -sys .maxsize - 1
    for i in range(mid + 1 , r + 1):
        sum_val += a [i]
        rmax = max (rmax , sum_val)
    return max(left , right , lmax + rmax)

if __name__ == "__main__":
    a1 = [-2 , 1 , -3 , 4 , -1 , 2 , 1 , -5 , 4]
    print(solve(a1 , 0 , len(a1)-1))
    a2 = [-5 , -3 , -1 , -4]
    print(solve(a2 , 0 , len(a2)-1))
    a3 = [10]
    print(solve(a3 , 0 , 0))
A.

O(n2)

B.

O(nlogn)

C.

O(logn)

D.

O(n)

2026-09-14
判断题

若一个问题满足最优子结构性质,则一定可以用贪心算法得到最优解。()

A.正确 B.错误
2026-09-14
公众号
客服 反馈
顶部