How to delete a character from a string using Python

前端 未结 16 1518
耶瑟儿~
耶瑟儿~ 2020-11-22 16:35

There is a string, for example. EXAMPLE.

How can I remove the middle character, i.e., M from it? I don\'t need the code. I want to know:

16条回答
  •  遥遥无期
    2020-11-22 17:15

    Strings are immutable. But you can convert them to a list, which is mutable, and then convert the list back to a string after you've changed it.

    s = "this is a string"
    
    l = list(s)  # convert to list
    
    l[1] = ""    # "delete" letter h (the item actually still exists but is empty)
    l[1:2] = []  # really delete letter h (the item is actually removed from the list)
    del(l[1])    # another way to delete it
    
    p = l.index("a")  # find position of the letter "a"
    del(l[p])         # delete it
    
    s = "".join(l)  # convert back to string
    

    You can also create a new string, as others have shown, by taking everything except the character you want from the existing string.

提交回复
热议问题