Indexing operators and string elements

Hi.

Can someone explain why I get an error -
Can I use and indexing operator to modify a string element like below

country = ‘Thailand’
country[-2] = ‘z’

Thanks

Like tuples, strings are immutable. You can’t do the above.

You can compute a new string though:

country = country[:-2] + 'z' + country[-1:]

Obviously country[-1:] will always be just a single character, but the
style would allow you to replace at almost arbitrary positions (the
start and end would require special handling).

To be clear: we’re using the same variable (country) but binding it to
a shiny new string object we just computed from the string it formerly
was. No different to:

x = x + 1

Ints are immutable too. We’re computing a new int and binding “x” to it.

Cheers,
Cameron Simpson cs@cskk.id.au

Hi Dan,

You ask:

“Can someone explain why I get an error”

Is the error message not clear enough? In Python 3.9 it says:

TypeError: 'str' object does not support item assignment

So the answers to your questions are no, you cannot using indexing to
modify strings, because strings do not support item assignment.

In other words, they are immutable (unchangeable).

If you would like to understand the reason why strings in Python are
immutable, that’s discussed in many places:

https://duckduckgo.com/?q=why+are+python+strings+immutable

including the FAQs itself:

https://docs.python.org/3/faq/design.html#why-are-python-strings-immutable

although I have to say (to my surprise!) the official Python answer in
the FAQ doesn’t even touch on the main reason why it is important that
strings (and ints) be treated as fundamental, elemental and unchangeable
values, which is to ensure that they are safely and sensibly useable as
dict keys.

Thanks Steven, really appreciate your help …
Cheers

Thanks Cameron,
that makes alot of sense,
Cheers

On re-reading my post, one of my comments didn’t come out right. I
asked:

“Is the error message not clear enough?”

I meant that to ask if there was something we could do to improve the
error message.

TypeError: 'str' object does not support item assignment

Thanks Steven…