Skip to content

Module 7 · Strings — topic 7 of 22

Immutability

Strings can’t be changed in place. Learn what that means, the TypeError you get when you try, how string methods return new strings, and the patterns for “modifying” text correctly.

Beginner 10 min read·Lesson 88 of 306 in Python Programming

Learning objectives

  • Explain string immutability
  • Create modified copies with slicing and methods
  • Recognise the bug of calling a method without saving its result

Definition

Strings can’t be changed in place. Learn what that means, the TypeError you get when you try, how string methods return new strings, and the patterns for “modifying” text correctly.

Introduction

Strings are immutable: once a string is created, its characters can never change. Operations that seem to modify a string, such as upper() or replace(), actually build and return a new string.

Why it matters

Immutability is the reason for one of the most common beginner bugs: calling name.upper() and expecting name to change. It also makes strings safe to share between parts of a program and lets them be dictionary keys.

Detailed explanation

Immutability also makes strings predictable when they are passed to functions. A function can never change the caller’s string, so you don’t need to make defensive copies of text before passing it on, unlike with lists and dictionaries.

Assigning to an index, s[0] = "J", raises TypeError: 'str' object does not support item assignment.

To change text, build a new string and rebind the name: s = "J" + s[1:].

Every string method that transforms text returns a new string and leaves the original alone. You must store or use the result: name = name.strip().

Because strings never change, two variables referring to the same string can’t affect each other.

Immutability makes strings hashable, so they can be dictionary keys and set members.

When you need to change many characters, convert to a list, modify the list, and join it back: chars = list(s); chars[0] = "J"; s = "".join(chars).

Syntax

Python
text = text.upper()
text = text[:i] + new_char + text[i + 1:]
  • Methods return new strings; assign the result.
  • Slicing and concatenation build modified copies.
  • The original string object is unchanged.

Code examples

Item assignment fails

Python
name = "Python"
try:
name[0] = "J"
except TypeError as err:
print("TypeError:", err)
name = "J" + name[1:]
print(name)
Output
TypeError: 'str' object does not support item assignment
Jython

Methods return new strings

Python
city = " pune "
city.strip().title()
print(repr(city))
city = city.strip().title()
print(repr(city))
Output
'  pune '
'Pune'

More examples

Masking and changing characters

Python
phone = "9876543210"
masked = "*" * (len(phone) - 4) + phone[-4:]
print(masked, phone)
chars = list("bat")
chars[0] = "c"
print("".join(chars))
original = "draft"
alias = original
original = original.upper()
print(original, alias)
Output
******3210 9876543210
cat
DRAFT draft

Step-by-step explanation

  • masked is a new string built from repeated stars and the last four digits; phone is unchanged.
  • list("bat") creates a mutable list of characters that can be changed, then joined back.
  • alias and original first refer to the same string.
  • original.upper() creates a new string and rebinds original; alias still refers to "draft".

Expected output

Running “Masking and changing characters” prints exactly:

TextOutput
******3210 9876543210
cat
DRAFT draft

Practical applications

  • Masking card and phone numbers creates new display strings without touching stored data.
  • Dictionary keys such as usernames rely on strings being immutable.
  • Text-processing pipelines chain methods, each returning a new string.

Best practices

  • Always assign or use the result of string methods.
  • Use slicing and concatenation for small changes.
  • Use a list of characters for many in-place edits.

Common mistakes

Calling a method without saving the result

Avoid

answer.lower()
if answer == "yes":

Prefer

answer = answer.lower()
if answer == "yes":

lower() returns a new string; the original variable is unchanged.

Trying to change one character by index

Avoid

word[2] = "x"

Prefer

word = word[:2] + "x" + word[3:]

Strings don’t support item assignment; build a new string.

Key takeaways

  • Strings can’t be changed after creation.
  • Methods and operations return new strings.
  • Rebind the variable to keep a modified version.

Try it yourself

  1. 1
    Replace the last character of a word with "!" using slicing.
  2. 2
    Show that s.upper() doesn’t change s by printing s before and after the call.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat happens when s = "cat" and then s[0] = "b" runs?
Practise this topic