← All lessons

replace and find

Sign in · Sign up

Lesson 4.6

replace replaces all occurrences of one piece of text with another, and find searches for the position where a substring starts:

text = "i learn python"
print(text.replace("i", "you"))   # you learn python
print(text.find("python"))        # 8
print(text.find("java"))          # -1

find returns the number of the first position it finds. If the substring is not there — -1, not an error. The text itself does not change after replace: strings are immutable.

The text, old, new and needle are provided by the check. Print in order:

  1. the text with old replaced by new;
  2. the position of needle in the original text.
Hint

.replace(old, new) returns a new string.

.find(substring) gives the number of the first occurrence or -1 if it is not found. Search in the original string, but print the replaced one first.