PTA每日一题-Python-删除字符

该博客探讨了如何在Python中删除字符串中的特定字符,无论其大小写。提供了三种不同的实现方法,包括使用`functools.reduce`、直接替换以及通过遍历和删除。示例中删除了所有'!'字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入一个字符串 str,再输入要删除字符 c,大小写不区分,将字符串 str 中出现的所有字符 c 删除。提示:去掉两端的空格。

输入格式:

在第一行中输入一行字符 在第二行输入待删除的字符

输出格式:

在一行中输出删除后的字符串

实现

#!/usr/bin/env python3                                                                                                         #-*- coding:utf-8 -*-
from functools import reduce
def method_1():
    try:
        #Transforming string to list type directly,it will include the char of ' ', but it isn't a trouble for this question's context.
        s=list(input())
        deleteChar=input().strip()
        print("result",reduce(lambda x,y:x+y,map(lambda x:'' if x.upper().__eq__(deleteChar.upper()) else x,s)).strip(),sep=":")
    except Exception as e:
        print("inputing error!",e,sep="\n")
def method_2():
    s=input()
    dec=input().strip()
    s=s.replace(dec.upper(),'')
    s=s.replace(dec.lower(),'')
    print("result:",s.strip())                                                                                                 
def method_3():
    i=0
    s=list(input())                                                                                                                          
    dec=input().strip()
    while i<len(s):
        if s[i].__eq__(dec.upper()) or s[i].__eq__(dec.lower()):
            s.remove(s[i])
            i-=1
        i+=1
    print("result:",reduce(lambda x,y:x+y,s).strip())
#-------
#method_1()
#method_2()
method_3()

输出

287343jhghjhgj1!hkjd!!!
!
result: 287343jhghjhgj1hkjd
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员杰森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值