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'))