0
0
Pythonprogramming~10 mins

Searching and replacing text 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 replace all occurrences of 'cat' with 'dog' in the text.

Python
text = 'The cat sat on the cat mat.'
new_text = text.[1]('cat', 'dog')
print(new_text)
Drag options to blanks, or click blank then click option'
Areplace
Bfind
Csplit
Djoin
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'find' instead of 'replace' which only finds the position.
Using 'split' or 'join' which do not replace text directly.
2fill in blank
medium

Complete the code to replace only the first occurrence of 'apple' with 'orange'.

Python
text = 'apple banana apple grape'
new_text = text.[1]('apple', 'orange', 1)
print(new_text)
Drag options to blanks, or click blank then click option'
Acount
Bfind
Creplace
Dindex
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'find' which only locates the substring.
Using 'count' or 'index' which do not replace text.
3fill in blank
hard

Fix the error in the code to replace 'blue' with 'red' in the string.

Python
text = 'blue sky'
new_text = text.[1]('blue', 'red')
print(new_text)
Drag options to blanks, or click blank then click option'
Areplace
BReplace
Creplac
Dsubstitute
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using capitalized method names like 'Replace'.
Misspelling the method name.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths as values, but only for words longer than 3 letters.

Python
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if len(word) [2] 3}
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
B<=
C>
Dword
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using the word itself instead of its length.
Using the wrong comparison operator.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys and their lengths as values, only for words longer than 4 letters.

Python
words = ['tree', 'house', 'car', 'elephant']
result = { [1]: [2] for w in words if len(w) [3] 4 }
print(result)
Drag options to blanks, or click blank then click option'
Aw.upper()
Blen(w)
C>
Dw
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using the word as key without uppercase.
Using wrong comparison operator or value.