How to delete a character from a string using Python

前端 未结 16 1368
耶瑟儿~
耶瑟儿~ 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.

    0 讨论(0)
  • 2020-11-22 17:16

    Use the translate() method:

    >>> s = 'EXAMPLE'
    >>> s.translate(None, 'M')
    'EXAPLE'
    
    0 讨论(0)
  • 2020-11-22 17:17

    Strings are immutable in Python so both your options mean the same thing basically.

    0 讨论(0)
  • 2020-11-22 17:20

    To replace a specific position:

    s = s[:pos] + s[(pos+1):]
    

    To replace a specific character:

    s = s.replace('M','')
    
    0 讨论(0)
  • 2020-11-22 17:20

    Another way is with a function,

    Below is a way to remove all vowels from a string, just by calling the function

    def disemvowel(s):
        return s.translate(None, "aeiouAEIOU")
    
    0 讨论(0)
  • 2020-11-22 17:25
    def kill_char(string, n): # n = position of which character you want to remove
        begin = string[:n]    # from beginning to n (n not included)
        end = string[n+1:]    # n+1 through end of string
        return begin + end
    print kill_char("EXAMPLE", 3)  # "M" removed
    

    I have seen this somewhere here.

    0 讨论(0)
提交回复
热议问题