5-3. Strings are Immutable

In Python, strings are immutable, meaning that once a string is created, it cannot be changed. Let's break this down with some simple examples.

What Does Immutable Mean?

When we say that strings are immutable, it means:

  • You cannot change the characters in a string directly.
  • If you want to change a string, you have to create a new string.

 

Example 1: Trying to Change a Character

Let's say we have a string:

If we try to change the first character 'H' to 'Y', it will give an error because strings are immutable:

>>> TypeError: 'str' object does not support item assignment

 

Example 2: Creating a New String

Instead of changing a string directly, we create a new string. For example, if we want to change "Hello" to "Yello", we can do this:

This code does the following:

  1. Takes the original string "Hello".
  2. Creates a new string "Yello" by combining "Y" with the substring "ello" (everything except the first character).
  3. Prints "Yello".

 

Example 3: Reassigning a Variable

If we reassign a string variable, we are not changing the original string; we are just making the variable reference a new string:

Here, we change message from "Good morning" to "Good evening". The original string "Good morning" remains unchanged in memory.

Example 4: Using String Methods

String methods like upper(), lower(), replace(), etc., do not change the original string but return a new string:

This code:

  1. Converts "hello world" to "HELLO WORLD" using the upper() method.
  2. Stores the result in new_text.

However, the original text variable is still "hello world".

In Python:

  • Strings cannot be changed after they are created.
  • To modify a string, you need to create a new string.
  • String methods return new strings and do not alter the original.