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)
>>> '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'
可以将map和join与lambda一起使用:
印刷品:
或者可以使用filter并使用lambda连接:
不需要加入输出,因为:
Python中的所有字符串都有一个
replace
函数。你知道吗您可以看到,它的功能非常类似于删除字母(或一系列字母)
但是如果您只想删除字母的第一个实例,或者字母的第一个
n
实例,可以使用第三个参数你甚至可以用一些诡计从末端移除,并反转字符串。你知道吗
如何使用
replace()
:相关问题 更多 >
编程相关推荐