How to delete all instances of a character in a string in python?

前端 未结 6 1886
清酒与你
清酒与你 2020-12-08 00:04

How do I delete all the instances of a character in this string? Here is my code:

def findreplace(char, string):
    place = string.index(char)
    string[pl         


        
6条回答
  •  借酒劲吻你
    2020-12-08 00:42

    I suggest split (not saying that the other answers are invalid, this is just another way to do it):

    def findreplace(char, string):
       return ''.join(string.split(char))
    

    Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below

    In[112]: findreplace('i', 'it is icy')
    Out[112]: 't s cy'
    

    And the speed...

    In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
    Out[114]: 0.9927914671134204
    

    Not as fast as replace or translate, but ok.

提交回复
热议问题