Home computickets Replace character at string index: TypeError: 'str' object does not support item...

Replace character at string index: TypeError: ‘str’ object does not support item assignment

Author

Date

Category

I’m a beginner in Python. It’s not clear why you can’t refer to a string by index.

sequence [geneNumber] = 0

Writes

'str' object doesn't support item assigment

Here is the link https://repl.it/Dojk/4


Answer 1, authority 100%

In Python, strings are immutable data types.
You can read from a string by index, but you cannot replace part of the string.

You can only create a new line from the old and new characters, and write the result to the same variable.

That is, you cannot do this:

s [num] = new_simbol

And so you can:

s = s [: num] + new_simbol + s [num + 1:]

This is also true for binary strings (as far as I understand, they are used in your code)


Answer 2, authority 36%

If you need to replace several characters, you can do this:

str = 'aaaaa'
str_list = list (str)
for i in [1,3]:
  str_list [i] = 'b'
str = '' .join (str_list)
# str = 'ababa'
Previous articleC++ Basic Calculator
Next articleCheck for JS number

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions