2

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 wonder whether there is a different efficient solution to the problem.

3 Answers 3

7

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:]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Makes sence. Imagine if your answer could get integrated into the python error message. And image if that error message was some kind of a community wiki so I could integrate it myself. I can accept the answer in 5 minutes.
@David: The immutability of certain basic Python types (especially strings and tuples) is something that baffles many newcomers to the language, but which makes a lot of sense and is a fundamental Python concept. After all, you don't expect to be able to change integer values in-place, either. So this is considered basic Python knowledge; the error message is clear enough for my taste.
I agree that it is clear, one cannot write everything in error message. But just imagine if all error messages contained a web link to a wiki page where all information/solutions about the problem could be included.
1

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..)

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.