Lecture 34:

posted Apr 3, 2013, 6:12 AM by Samuel Konstantinovich   [ updated Apr 4, 2013, 6:02 AM ]
GOAL: wake up your brains, then split and join (not your brains)

Do now: Write a replace function that acts like the replace method of strings

replace(startingText,oldString,newString, maxReplaces)  
The function returns the startingText string with at most maxReplaces instances of oldString replaced with newString.

Examples:
replace("blahblahblah","ah","o",2) returns "blobloblah"
replace('the world is mine','e','3',100) returns "th3 world is min3"

Just in case you didn't know the built in method: (you don't write this version)
"blahblahblah".replace("ah","o",1)  returns "bloblahblah"
"blahblahblah".replace("ah","o",2)  returns "blobloblah"

SAMPLE SOLUTIONS:

#using the find method
def replace(startString,oldString,newString,maxReplaces):
    #tell the loop to start looking here
    start=0
    while oldString in startString[start:] and maxReplaces>0:
            #find the string
            index=startString.find(oldString,start)

            #calculate where to start looking next
            start=index+len(newString)
            
            #replace it
            startString=startString[:index] + newString + \
                         startString[index+len(oldString):]

            #reduce the number of replacements allowed
            maxReplaces-=1
            
    return startString

#without find
def replace(startString,oldString,newString,maxReplaces):
    #tell the loop to start looking here
    start=0
    while start <= len(startString)-len(oldString) and maxReplaces>0:

        
            #should you replace?
            if startString[start:start+len(oldString)]==oldString:                

                #replace it
                startString=startString[:start] + newString + \
                             startString[start+len(oldString):]

                #reduce the number of replacements allowed
                maxReplaces-=1

                #shift over by the number of characters you just replaced
                start+=len(newString)
            else:
                start+=1
            
    return startString



New Features:
#split breaks a string up into multiple strings.
#The parameter is which string you break on.
print "The rain in spain falls mainly on the plains".split(" ")
print "Hells bells wells fells".split("ll")


#join is the opposite operation, it takes a list of
#strings, and puts them together with a specific string between them
print 'ABC'.join(['super','fighting-robot','Megaman!'])
print '\n'.join(['These words','will be joined','by newlines'])

Comments