Python: Delete a character from a string

前端 未结 3 679
深忆病人
深忆病人 2021-01-23 03:34

I want to delete i.e. character number 5 in a string. So I did:

del line[5]

and got: TypeError: \'str\' object doesn\'t support item deletion

So no I won

相关标签:
3条回答
  • 2021-01-23 04:00

    bytearray is a type which can be changed in place. And if you are using Python2.x, it can very easily convert to default str type: bytes.

    b=bytearray(s)
    del b[5]
    s=str(b)
    
    0 讨论(0)
  • 2021-01-23 04:09

    Strings are immutable in Python, so you can't change them in-place.

    But of course you can assign a combination of string slices back to the same identifier:

    mystr = mystr[:5] + mystr[6:]
    
    0 讨论(0)
  • 2021-01-23 04:25

    I use a function similar to :

    def delstring(mystring, indexes):
      return ''.join([let for ind, let in enumerate(mystring) if ind not in indexes])
    

    indexes should be an iterable (list, tuple..)

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