CSC111 Lab 6 2011
This lab deals with Strings, string variables as object instantiated from the class String, which sports many different and useful methods.
The methods are all documented at this page: http://docs.python.org/py3k/library/stdtypes.html. Open this page and refer to it while you are working on this lab.
Use emacs or the python interactive prompt to test out different methods.
One of the string methods is the center function. A few people discovered it and used it in the last homework assignment...
Use it to center the title "computer SCIENCE 111" between two lines of 45 dashes. Use a variable called myTitle to store the string.
myTitle = "computer SCIENCE 111" print( 45*"-" ) print( myTitle.center( 45 ) ) print( 45*"-" )
Instead of printing the variable myTitle, print myTitle.lower( ) and see what happens.
Same thing with Method upper()...
Instead of printing the variable myTitle, print myTitle.capitalize( ) and see what happens.
Use upper() instead of capitalize(). Observe the new output.
Same exercise, but with the title() method.
- Write some Python code that will ask for your name, then your last name, and will print both of them centered between two lines of 60 dashes. Make your program capitalize the first letter of each word.
your first name? alexAndra your last name? SMITH ------------------------------------------------------------ Alexandra Smith ------------------------------------------------------------
Replacing substrings in a string
To replace a substring of a string (or a word in a sentence), all you need to do is to use the replace() method.
sentence = """Strength is the capacity to break a chocolate bar into four pieces with your bare hands - and then eat just one of the pieces""" print( sentence ) sentence = sentence.replace( "chocolate", "carrot" ) print( sentence )
Try it and replace the word "piece" by the word "chunk" in the same sentence, so that now you're breaking carrots into chunks.
We are still dealing with the sentence above, but we want to replace four separate words by four new words. The words we want to replace are in this list:
toBeReplaced = ["chocolate", "piece", "hand", "break"]
and the replacement words are in this list:
newWords = ["carrot", "chunk", "elbow", "melt"]
Write python statements that will take the string sentence and replace chocolate by carrot, then it will look for piece and replace it by chunk, hand by elbow, and break by melt.
Use a for-loop, something inspired by this code...
sentence = """Strength is the capacity to break a chocolate bar into four pieces with your bare hands - and then eat just one of the pieces""" oldStr = [ "chocolate", "piece", "hand", "break" ] newStr = [ "carrot", "chunk", "elbow", "melt" ] for i in range( len( oldStr ) ): print( oldStr[ i ], newStr[ i ] )
Read the documentation on the method count() and write some statements that output the number of times the word "piece" appears in sentence using the count() method.
Read the documentation about the method strip() and use it to allow you to print the lines below left aligned.
listOfStrings = [ " But then, shall I never get any older than I am now? ", " That'll be a comfort, one way -- never to be an old woman -- ", " but then -- always to have lessons to learn! ", " Alice " ]
First, read the documentation on the split() method.
Let's use the same string as before.
sentence = """Strength is the capacity to break a chocolate bar into four pieces with your bare hands - and then eat just one of the pieces"""
And process it that way
list1 = sentence.split( "\n" ) print( "list1 = ", list1 ) list2 = sentence.split( ) print( "list2 = ", list2 ) list3 = sentence.split( 's' ) print( "list3 = ", list3 )
- Make your program print the number of words in sentence (there are several ways to do that: one long, one very short).
- Make your program display the first and last words of the sentence. (Remember that you can use negative indexes to pick elements of a list starting from its end.)
- Assume that you have a string of this type:
NYTBestSellers = """1. THE HELP, by Kathryn Stockett 2. WORST CASE, by James Patterson and Michael Ledwidge 3. THE LOST SYMBOL, by Dan Brown 4. POOR LITTLE BITCH GIRL, by Jackie Collins 5. WINTER GARDEN, by Kristin Hannah """
- Write the code that will take this string, process it, and output the information in a different format, shown below:
Kathryn Stockett: 1. The Help James Patterson and Michael Ledwidge: 2. Worst Case Dan Brown: 3. The Lost Symbol Jackie Collins: 4. Poor Little Bitch Girl Kristin Hannah: 5. Winter Garden
Graphics and Simple Animation
- Create a new program with the following code:
w = 600
h = 400
win = GraphWin( "moving!", w, h )
c1 = Circle( Point( 30, 30 ), 20 )
c1.setFill( "black" )
c1.draw( win )
speedX = 5
speedY = 2
for i in range( 100 ):
c1.move( speedX, speedY )
# time.sleep( 0.01 ) # wait 1/100th of a sec
- Modify the program so that C1 disappears from the window. Feel free to pick a different direction than the one I used here.
- Next, add a new loop and make C1 come back to the window by retracing its steps. It has to be the reverse direction from the one it left the window with.
- Next, add a new circle inside C1, called C2, with a different color. Modify your two loops so that both circles move together out of the screen and back in. We'll call the set of C1 and C2 together a wheel...
- Add another wheel to your program and make your loops move both of them together, outside the window, and back inside the window. The distance between the two wheels should remain the same (i.e. they have the same x and y speed components).
- Finish this section by adding a yellow rectangle, as the body of the taxi (no need for windows or text labels), and make it go out of the window, and back in.
Some Exam Questions to Help You Prepare
def main(): x = input( "> " ) y = eval( input( "> " ) ) print( x*y ) print( eval(x)-y ) main()
- What did the user enter at the prompts, when the output of the program is
def main(): x = eval( input( "> " ) ) y = eval( input( "> " ) ) print( x + y ) print( x - y ) main()
- The program outputs 0 and -2. What numbers did the user enter?
def main(): for i in range( 3 ): print( i, end=" " ) # a space for j in range( 3-i ): print( j, end= "-" ) # a dash print() main()
- What is the output of the program?
- The loop below will print all the animals in the farm:
farm = [ "pig", "hen", "horse", "dog", "cat", "duck", "mouse" ] for i in range( len( farm ) ): print( farm[ i ] )
- Write the code that will output the same list, but starting with mouse and ending with pig. You cannot modify the list farm.
- Write the code that will output only every other animal, starting with the pig.
- Write the code that will output only every other animal, starting with the dog.
- Write a program that computes the sum of all the integer numbers between 1 and 1000, 1 and 1000 included.
- Same question, but compute the sum of only the even numbers.
Playing with Pixels (Optional)
- Get the pixelation program we saw in class in the last lecture and use it to redraw George Clooney's image with various transformations:
- make the red component of the RGB values of each pixel 0 and redraw each pixel with the new value. You will have to use the setPixel( X, Y, color ) method for the Image to change each pixel color. Note: this will be very slow!
- make the green component of the RGB values of each pixel half its original value and redraw each pixel with the new value.
- For each pixel in the image, get the RGB value for each pixel, then set its color to GBR, i.e. swapping green for red, blue for green, and red for blue.
- draw a white border around the image, and make it 10 pixels wide.
There is no homework assignment this week. We will resume working on homework assignment starting Tuesday night, after the midterm exam.