Introduction
Strings cannot be changed after they are created. This helps keep data safe and predictable.
Jump into concepts and practice - no test required
Strings cannot be changed after they are created. This helps keep data safe and predictable.
s = "hello" s[0] = "H" # This will cause an error
You cannot change a single character in a string directly.
To change text, you create a new string instead.
s = "hello" # Trying to change a character causes error # s[0] = "H" # TypeError: 'str' object does not support item assignment
s = "hello" s = "H" + s[1:] print(s) # Output: Hello
s = "hello" new_s = s.replace('h', 'H') print(new_s) # Output: Hello
This program shows that changing a string character directly causes an error. Then it shows how to create a new string with the desired change.
s = "hello" try: s[0] = "H" except TypeError as e: print(f"Error: {e}") # Correct way to change string s = "H" + s[1:] print(s)
Strings are like printed words on paper; you cannot erase a letter but you can write a new paper.
Always create a new string if you want to change text.
Strings cannot be changed after creation.
To change text, make a new string from parts or methods.
This helps keep your program safe and easy to understand.
immutable?word = 'hello' to uppercase?word[0] = 'H'.'H' + word[1:] makes a new string with first letter changed.text = 'cat' text[0] = 'b' print(text)
text[0] = 'b' attempts to change a character in the string.TypeError.word with 'J'. What is wrong and how to fix it?word = 'python' word[0] = 'J' print(word)
word[0] is invalid because strings cannot be changed by index.word = 'J' + word[1:].s = 'banana', how can you create a new string where all 'a' characters are replaced by 'o' without modifying s directly?s.replace('a', 'o') returns a new string with all 'a' replaced by 'o'.