0
0
Pythonprogramming~10 mins

String immutability in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new string by replacing the first character.

Python
text = "hello"
new_text = [1] + text[1:]
print(new_text)
Drag options to blanks, or click blank then click option'
A"j"
Bj
C'j'
D"hello"
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using a character without quotes causes an error.
Trying to assign directly to a string index.
2fill in blank
medium

Complete the code to show that strings cannot be changed by assignment.

Python
text = "hello"
try:
    text[0] = [1]
except TypeError:
    print("Cannot change string characters directly")
Drag options to blanks, or click blank then click option'
A'j'
B"j"
Cj
D"hello"
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using an unquoted character causes a NameError.
Trying to assign to string index without quotes.
3fill in blank
hard

Fix the error in the code that tries to change a string character.

Python
word = "world"
word = [1] + word[1:]
print(word)
Drag options to blanks, or click blank then click option'
A"W"
B'W'
CW
D"world"
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using an unquoted character causes an error.
Trying to assign directly to string index.
4fill in blank
hard

Fill both blanks to create a new string with the last character replaced.

Python
word = "python"
new_word = word[:[1]] + [2]
print(new_word)
Drag options to blanks, or click blank then click option'
A-1
B"!"
C5
D'!'
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 6 as slice index includes the last character.
Using unquoted character causes error.
5fill in blank
hard

Fill all three blanks to replace the middle character in a string.

Python
word = "apple"
new_word = word[:[1]] + [2] + word[[3]:]
print(new_word)
Drag options to blanks, or click blank then click option'
A2
B"i"
C3
D'i'
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using wrong slice indexes.
Using unquoted replacement character.