find() function

find()
 
function 
returns 
the 
<code>index<code> 
of 
the 
searched 
character 
in 
a 
string. 
In 
the 
case 
of 
a 
substring 
that 
is 
a 
part 
of 
the 
string, 
find() 
returns 
the 
index 
of 
the 
first 
character 
of 
a 
searched 
substring 
in 
a 
string.
It 
returns 
-1 
if 
the 
substring 
or 
character 
searched 
for 
is 
not 
present 
in 
the 
given 
string. 
In 
the 
case 
of 
more 
than 
one 
occurrence 
of 
the 
substring, 
it 
returns 
the 
index 
of 
the 
first 
occurrence.
string.find(<letter / substring to be searched>)
string = 'starry sky'
print(string.find('a'))

line = 'Kate on her skateboard!'
print(line.find('Kate'))
line = 'Kate on her skateboard!'
print(line.find('Katie'))
line = 'Kate on her skateboard!'
print(line.find('ate'))
#there are 2 ""ate"" substrings in variable line, but python shows the starting index of the first occurence.

replace() function

replace()
 
function 
replaces 
a 
specified 
character 
or 
substring 
with 
another 
in 
a 
string.
We 
can 
also 
specify 
the 
number 
of 
times
 
the 
character 
or 
substring 
needs 
to 
be 
replaced.
If 
count 
is 
not 
specified 
python 
replaces 
all 
the 
occurrences
string.replace('oldWord','newWord',count)

#oldWord is a word you want to replace
#newWord is a word you want to replace with
#count is the number of times you want to replace oldWord with newWord
line = "O’really? bababa!"
print(line.replace('ba', 'ha'))

line = "O’really? bababa!"
print(line.replace('ba', 'ha', 2))
#We can also replace two words in one go
line = 'I saw Dave on his bicycle.'
print(line.replace('Dave', 'Donna').replace('his', 'her'))