DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

Why are Strings Immutable in Python?

Immutable means we cannot change the original string after creating it.

In Python, strings are immutable because Python does not allow us to modify individual characters of an existing string.

  1. Example:

name = "Python"
name[0] = "J"
print(name)

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

Why?

Because we are trying to change the first character of the existing string from P to J.

Python does not allow this.

  1. How can we change a string?

We cannot modify the original string, but we can create a new string.

name = "Python"
name = "J" + name[1:]
print(name)

Output:
Jython

Top comments (0)