Lecture 35:

posted Apr 4, 2013, 6:01 AM by Samuel Konstantinovich   [ updated Apr 9, 2013, 12:49 PM ]
Find the syntax errors in this code, write a correction for it.
def madness(a,b,c):
    i=0
    while i<b
        a+=c
    i+=1
    if a=>100:
        print "Big number:"+a
        else:
            print 'too small to care'

Evaluate each expression: 
1. 3*('abc'.replace('b','x',2))
2. (3*'abc').replace('b','x',2)
3. "Spartans".split('a')
4. 'x'.join( [ 'a','e','_','i' ] )
5. 'batter'.find('T')
6. 'Hey'.swapcase().find('E')
7. "abba".split('a')

REMINDERS: 
1. Homework (madlibs) due on homework server tomorrow 1159pm.
2. Test Friday! 
3. Notify me via email if you submit old homeworks to the homework server, or I won't check them.

NEW STUFF:

text0='''Hey! listen!
Hey, Hey, Hey!
Listen!
Please: Listen!!!'''
wordList=text0.split(" ")

#How can we split all of the words in this text?
#How can we remove the punctuation from the words?

print wordList

regarding split:

split has 2 optional parameters:
text.split( [ separator] [, maxSplits ] )

maxSplits is the upper limit of separations that will be made.
separator is the string that will be used as the place to split.

if you leave out the separator split works with a different algorithm:
Every block of whitespace acts as a SINGLE separator! This is really useful. Tab,Space,NewLines (in any quantity) will make one separator.

SOLUTIONS: (3 versions of the strip code, you only need one )
text0='''Hey! listen!
Hey, Hey: Hey!
Listen!
Please:         Listen!!!'''


#How can we split all of the words in this text?

wordList=text0.split()

#How can we remove the punctuation from the words?

#using a for loop (index type for loop)
for i in range(len(wordList)):
    wordList[i]=wordList[i].strip('!,:;?.')

#OR using a while
i=0
while i<len(wordList):
    wordList[i]=wordList[i].strip('!,:;?.'))
    i+=1

#OR by using a second list (either for or while) then copying it to wordList
temp = []
for a in wordList:
    temp.append(a.strip('!,:;?.'))
wordList=temp

print wordList


Comments