SEARCH AND REPLACE A STRING IN OTHER STRINGS
Python provides methods for searching and also for replacing a string in a second text string. Listing A.4 displays the contents of FindPos1.py that shows you how to use the find function to search for the occurrence of one string in another string.
Listing A.4: FindPos1.py
item1 = 'abc'
item2 = 'Abc'
text = 'This is a text string with abc'
pos1 = text.find(item1)
pos2 = text.find(item2)
print('pos1=',pos1)
print('pos2=',pos2)
Listing A.4 initializes the variables item1, item2, and text, and then searches for the index of the contents of item1 and item2 in the string text. The Python find() function returns the column number where the first successful match occurs; otherwise, the find() function returns a -1 if a match is unsuccessful. The output from launching Listing A.4 is here:
pos1= 27 pos2= -1
In addition to the find() method, you can use the in operator when you want to test for...