September 28, 2006
The purpose of today's lab is to try out some string functions, and work with decision structures.
Get a copy of the file lab4.pyc from my handout directory (with the command getcopy lab4.pyc)Use emacs to write your own version of the program.
This is not a deep, meaningful program. It's just a way
to try out some of python's functions and statements.
I have broken it into three parts. Get each part to work first
before moving on the the next part.
Here is what your program should do:
Part 1.
We just demonstrated some string manipulationsGet all of this part to work before moving to Part 2.
Part 2.
len(canned)as the second parameter. What is the first parameter? Think of the possible index values of a list.
Part 3. Now try out the if statment
Type the following statements at the end of your lab4.py main() function definition:
computer = ""
for word in message:
old_word = word
word = string.replace(word,"I","You")
if old_word==word:
word = string.replace(word, "You", "I")
computer = computer + word + " "
print computer
This code takes each word from the sequence
user_words, and first places the word in a variable called
old_word, for safe-keeping.
word = string.replace(word,"I","You")
finds all occurrences of the string "I" in word, and
replaces it with "You". The variable word will only
contain one word so it is either replaced or not.
It then assigns the resulting string to the variable
word.
The next line is the beginning of an if statement
if old_word==word:
it checks if old_word and word are the same using the
equality operator (==). This is a nice feature of python.
If they are the same, then no replacement happened.
In that case, we want to try
word = string.replace(word, "You", "I")
and if the word contains "You", we'll replace it with
"I" and assign the new string to word.