Skip to content
Home » String Immutability in Python

String Immutability in Python

Spread the love

Today we’ll be talking about string immutability.

Here you can watch the video version of this article:

Strings are immutable. Once defined, they can’t be changed.

We can’t change any of the characters. For example we can’t change Jake to Jane by changing ‘k’ to ‘n’. If we try, we’ll get a self-explanatory type error:

>>> name = "Jake"
>>> name[2] = "n"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

We can assign a new object to a variable, but this is not changing the string. This way we are just defining a new string and assigning it to the same variable:

>>> text = "I like soccer."  # the string is assigned to text 
>>> text = "I like tennis."  # a new string is assigned to text
>>> text
'I like tennis.'

String immutability also means that you can’t delete a single character either. If we try to do that, using the del statement, we’ll get an error:

>>> name = "Steve"
>>> del name[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

We can delete the whole string:

>>> del name
>>> name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply