String is Immutable

In Python, strings are immutable, which means once a string is created, its individual characters cannot be changed or replaced using indexing or assignment.

This immutability ensures that string objects remain constant and secure in memory. Any attempt to modify a string directly will result in an error. If any modification is needed, a new string must be created based on the required changes.

Example of Invalid Modification:

name = "Peehu"
name[0] = "R"          # This will raise an error

Output:

TypeError: 'str' object does not support item assignment

Explanation:

  • Strings are immutable – their characters can't be altered directly using index positions.
  • Here, we tried to change the first character 'P' to 'R'.
  • Python does not allow direct item assignment for strings, so it raised a TypeError.

Real-life Analogy:

Think of a string as a printed name on a paper. You can’t erase a single letter and write another; you need to print a new sheet with the correct name.

Correct Way (Create a New String):

name = "Vansh"
new_name = "Y" + name[1:]
print(new_name)

Output:

Yash

Explanation:

  • We are not modifying the original string name directly.
  • Instead, we created a new string by concatenating "Y" with name[1:].
  • name[1:] returns all characters except the first one, and "Y" is added before it.
  • This way, the desired change is achieved without violating immutability.

Summary:

  • Strings in Python are immutable – their characters cannot be changed after creation.
  • Any modification must be done by creating a new string.
  • Trying to change characters directly using indexing causes a TypeError.
  • Use slicing and concatenation to build modified versions of strings.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar