Complete the code to replace all occurrences of 'cat' with 'dog' in the string.
text = 'The cat sat on the cat mat.' new_text = text.[1]('cat', 'dog') print(new_text)
The replace() method replaces all occurrences of a substring with another substring in a string.
Complete the code to replace only the first occurrence of 'apple' with 'orange' in the string.
text = 'apple banana apple grape' new_text = text.[1]('apple', 'orange', 1) print(new_text)
The replace() method can take a third argument to limit how many replacements happen. Here, 1 means only the first 'apple' is replaced.
Fix the error in the code to replace 'blue' with 'red' in the list of colors.
colors = ['blue', 'green', 'blue'] new_colors = [color.[1]('blue', 'red') for color in colors] print(new_colors)
Strings have the replace() method. We use it inside a list comprehension to replace 'blue' with 'red' in each string.
Complete the code to create a dictionary with words as keys and their lengths as values, but only for words longer than 3 letters.
words = ['sun', 'moon', 'star', 'sky'] lengths = {word: [1] for word in words if len(word) > 3} print(lengths)
In dictionary comprehension, the key and value are separated by a colon :. The value here is the length of the word using len(word).
Fill all three blanks to create a dictionary with uppercase words as keys and their lengths as values, but only for words longer than 3 letters.
words = ['sun', 'moon', 'star', 'sky'] result = { [1]: [2] for word in words if len(word) [3] 3 } print(result)
The dictionary comprehension uses word.upper() as keys, len(word) as values, and filters words with length greater than 3 using >.