SEARCH AND REPLACE A STRING IN OTHER STRINGS
Python provides methods for searching and replacing a string in a second text string. Listing 1.4 displays the content of find_pos1.py that shows you how to use the find function to search for the occurrence of one string in another string.
LISTING 1.4: find_pos1.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 1.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 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 1.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 the presence of an element, as shown here:
>>> lst = [1,2,3] >>> 1 in lst True
Listing 1.5 displays the content of replace1.py that shows you how to replace one string with another string.
LISTING 1.5: replace1.py
text = 'This is a text string with abc'
print('text:',text)
text = text.replace('is a', 'was a')
print('text:',text)
Listing 1.5 starts by initializing the variable text and then printing its contents. The next portion of Listing 1.5 replaces the occurrence of “is a” with “was a” in the string text, and then prints the modified string. The output from launching Listing 1.5 is here:
text: This is a text string with abc text: This was a text string with abc