String Immutability in Python #
In Python, a string is an immutable object, which means that once a string is created, it cannot be modified.
For example, consider the following code:
string = "Hello, world!"
string[0] = "h"
This code will result in a TypeError: 'str' object does not support item assignment, because we are trying to modify a character in the string, which is not allowed.
Instead of changing a character in a string, we can create a new string and reassign it to the same variable, like so:
string = "Hello, world!"
string = "hello, world!"
print(string) # hello, world!
Example #
- Update the code so that the
stringvariable is"How are you doing?" - Keep the first line of the code the same
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules