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

前端 未结 6 1906
清酒与你
清酒与你 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:33

    >>> x = 'it is icy'.replace('i', '', 1)
    >>> x
    't is icy'
    

    Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1 argument.

    Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)

提交回复
热议问题