删除已知ch

2024-04-26 22:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

刚接触python,所以希望能得到一些帮助。 尝试构建一个函数(到目前为止失败了),它的目的是从单词中删除一个指定的字母,然后返回结果。你知道吗

示例:

word_func('bird', 'b')

然后返回的结果将给出'ird',其中b被删除。你知道吗

我要重新开始的功能是:

def word_func('word', 'letter'):

任何帮助都将不胜感激。我想我把这件事想得太复杂了。你知道吗


Tags: 函数目的功能示例def字母单词word
3条回答

可以将mapjoinlambda一起使用:

def word_func(word, letter):
    return "".join(map(lambda x: x if x !=letter else "",word))


if __name__ =="__main__":
    word = "bird"
    letter = "r"
    print word_func(word, letter)

印刷品:

bid

或者可以使用filter并使用lambda连接:

def word_func(word, letter):
    return filter(lambda x: x !=letter, word)

不需要加入输出,因为:

If iterable is a string or a tuple, the result also has that type

Python中的所有字符串都有一个replace函数。你知道吗

>>> 'bird'.replace('b', '')
'ird'

您可以看到,它的功能非常类似于删除字母(或一系列字母)

>>> 'bird'.replace('bi', '')
'rd'

但是如果您只想删除字母的第一个实例,或者字母的第一个n实例,可以使用第三个参数

>>> 'this is a phrase'.replace('s','') # remove all
'thi i a phrae'
>>> 'this is a phrase'.replace('s','',1) # remove first
'thi is a phrase'
>>> 'this is a phrase'.replace('s','',2) # remove first 2
'thi i a phrase'

你甚至可以用一些诡计从末端移除,并反转字符串。你知道吗

>>> 'this is a phrase'[::-1].replace('s','',2)[::-1] # remove last 2
'this i a phrae'

如何使用replace()

>>> def word_func(word, letter):
...     return word.replace(letter, '')
... 
>>> word_func('bird', 'b')
'ird'

相关问题 更多 >