Python Programming Exercises, Gently Explained
31
to replacedText.
Create a while loop starts a variable named i at 0 and then keeps looping until i reaches the
length of the text string argument. This i variable points to an index in the text string. The code
inside the loop increases i by the length of oldText if it has found an instance of oldText in
text
. Otherwise the code inside the loop increases i by 1 so it can examine the next character in
text
.
The code inside the loop can examine the slice text[i:i + len(oldText)] to see if it
matches oldText. In that case, we append newText to replacedText and increase i by 1. If not,
we append just the text[i] character to replacedText and increase i by len(oldText). By
the time i reaches the end of text, the replacedText variable contains the finished string.
Figure 10-1 shows each step of this process if we were to call findAndReplace('A fox.',
'fox', 'dog')
.
Figure 10-1: Replacing 'fox' with 'dog' in 'A fox.'
Python has
augmented assignment operators such as += and *=. These are shortcuts for assignment
statements that modify the value in a variable. Python has augmented assignment operators for several
operators:
Dostları ilə paylaş: