String Immutability and Its Implications¶
CS 5001/5002 - Strings, Sequences & Sets
Code¶
#!/usr/bin/env python3
"""
Filename: string_immutability.py
Description: String Immutability and Its Implications
CS 5001/5002 - Strings, Sequences & Sets
This script demonstrates the immutable nature of strings in Python and
compares them with other immutable sequences like tuples.
"""
def main():
# Strings are immutable
text = "hello"
print(f"Original text: {text}")
# This creates a NEW string, doesn't modify the original
new_text = text.upper()
print(f"After upper(): original = '{text}', new = '{new_text}'")
# Trying to modify a string character raises an error
try:
text[0] = 'H' # This will fail!
except TypeError as e:
print(f"Error: {e}")
# String concatenation creates new strings
greeting = "Hello"
name = "World"
message = greeting + " " + name # Creates new string
print(f"Concatenated: '{message}'")
# Tuples are also immutable sequences
weekdays = ("Mon", "Tue", "Wed", "Thu", "Fri")
print(f"Weekdays tuple: {weekdays}")
print(f"First weekday: {weekdays[0]}")
if __name__ == "__main__":
main()
How to Use¶
- Copy the code above
- Save it as a
.pyfile (e.g.,string_immutability.py) - Run it with:
python string_immutability.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials