8. Replace
replace() returns a copy of a string with some text swapped for other text. Its signature is:
old— the text to look for. It can be one character or a longer substring.new— the text that replaces each occurrence.count— the maximum number of replacements, counted from the left. Default:-1, which replaces every occurrence.
replace() returns a new string and leaves the original unchanged. Replacing old with "" (an empty string) deletes every occurrence.
Coming from JavaScript? replace() replaces every occurrence by default. JS replace() replaces only the first unless you use a global regex.
Replace a word
replace(old, new) returns a new string with every occurrence of old changed to new.
Print "Hello world" with "world" replaced by "Python".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Replace every occurrence
With no count argument, replace() changes every occurrence in the string.
Print "a-b-c" with every "-" replaced by a space.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Limit the replacements
The third argument of replace(old, new, count) is the maximum number of replacements, counted from the left.
Print "a-b-c" replacing only the first "-" with a space.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Delete a substring
Replacing text with "" (the empty string) removes it.
Print "banana" with every "na" removed.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
The original does not change
replace() returns a new string; the variable you call it on keeps its value.
Create a variable named word with the value "cat". Print word with "c" replaced by "b", then print word again on a second line.
Print exactly:
Create a free account to save your progress and unlock chapter 2.