# string_puzzle_df_soln.py # Lillian Lee (LJL2) and Steve Marschner (SRM2) # Jan 30, 2014 #using import to access function 'capwords' import string """ Two solutions to the 'df' puzzle we didn't get to in lecture. Also demonstrate using a function from the 'string' module. Given: variable info contains a comma-separated string with last name, difficulty, execution, and penalty scores. Goal: store the difficulty as a string, with no extra spaces or punctuation, in variable df """ # Let's use the example from lecture info = 'RAISMAN, 6.7, 9.1,0' # Solution presented in lecture startcomma = info.index(',') tail = info[startcomma+1:] # substring of info starting after 1st comma endcomma = tail.index(',') df = tail[:endcomma].strip() print 'first solution: df is "' + df + '"' # version with debugging prints # recall that "str" converts its argument to a string # #print "start comma is:" + str(startcomma) + ":" #tail = info[startcomma+1:] #print "tail is:" + tail + ":" #endcomma = tail.index(',') #print "endcomma is:" + str(endcomma) + ":" #df = tail[:endcomma-1].strip() #print 'in this solution: "' + df + '"' # More compact but less readable solution df = info[info.find(',')+1:info.find(',',info.find(',')+1)].strip() print 'alternate solution: df is "' + df + '"' # This is NOT ACTUALLY A SOLUTION, because it makes assumptions about # the number of spaces. # Using strip is better - safeguards against the random spaces people type startcomma = info.index(',') tail = info[startcomma+2:] # substring of info starting after 1st comma and following space endcomma = tail.index(',') df = tail[:endcomma] print 'accidentally correct but non-general solution: df is "' + df + '"' #using a function from the 'string' module print 'version of info w/ diff capitalization: "' + string.capwords(info) + '"'