Chapter 17: Find and Replace method

The replace() method is used to replace specific text or characters in a given string with new text or characters.

 

name        = "Free Learning"
namereplace = name.replace("e","E") # replacing all e to E
print(namereplace)
Output: FrEE LEarning
namereplace = name.replace("e","E",2) # replacing first two e to E
print(namereplace)
Output: FrEE Learning

 

The find() method is used to locate the position (index) of a specified value within a string. If the value is not found, it returns -1.

 

name        = "Free Learning"
namefind_e1 = name.find("e") # finding the position of first e
print(namefind_e1)
Output: 2
namefind_e2 = name.find("e",namefind_e1+1) # finding the position of second e
print(namefind_e2)
Output: 3
namefind_e1 = name.find("M") # Not Found
print(namefind_e1)
Output: -1