2014-03-10

posted Mar 10, 2014, 5:07 AM by Samuel Konstantinovich   [ updated Mar 10, 2014, 5:07 AM ]
Goal: Slicing strings!

DO NOW:
You have 2 minutes: discuss with your neighbor your conclusions about  stringVariable[a:b] notation while getting the classwork pasted into a new file in idle.
Classwork:

Copy/Paste the sample code, run it and follow the directions.
#________________________________START SAMPLE CODE________________________________________
def makeSentence(greeting,firstName,lastName,catchPhrase):
    return greeting+". My name is "+firstName+" "+lastName+". "+catchPhrase+"!"

first ="Inigo"
last = "Montoya"
greet = "Hello"
phrase = "You killed my father, prepare to die"

s1= makeSentence(greet,first,last,phrase)
s2= makeSentence("Much merryment and festivities to you sir","Die","O'nisus","Sit down and enjoy the feast")

print "use the variable s1:"
print "'"+s1+"'"
print "Use the string slice notation on variable s1 to print the following things(with no extra spaces)"
print "1. Just print 'Hello'"
print "2. Now print just 'My name is' (with no extra spaces)"
print "3. Finally print the last part of the sentence starting at 'Inigo' until the end of the string without the '!' at the end"
print "4. What would be useful information to have ahead of time to be able to complete number 3 more easily?"
#________________________________END SAMPLE CODE________________________________________

Classwork 2:

Examples 1-3 Should be done on paper!!!
In pairs/triples, consider the code below, trace through it and decide what the output is:
Each person should have a diagram of how they traced it out, with the string being built step by step.
(This is exactly the kind of question you might see on a test, take it seriously)

EXAMPLE 1.

s2="Infinity and Beyond!"
x=0
s3=""
while x<len(s2):
    s3=s3+s2[x]+" "
    x=x+1
print s3

EXAMPLE 2.

s4="Dr.Who?"
x=0
s5=""
while x<len(s4)-2:
    s5=s5+s4[x:x+2]
    x=x+1
print s5

EXAMPLE 3.

s6="oragif"
index = 0
newString=""
while index < len(s6):
    newString = newString + s6[len(s6)-index-1]
    index=index+1
print newString
Comments