""" Purpose: do some functions produces lists from a string """ def ints( ns ) : """ Returns list of integers corresponding to the integer substrings in ns. """ # ** this function assumes that ns is a valid numeric string ** result = [] # since we're accumulating the answer, we initialize result to an empty list num_strings = ns.split() # since ns is a string, we convert it to a list for processing # split() will handle extra whitespace between numbers for n_str in num_strings : number = int( n_str ) # convert each numeric string to an integer result.append( number ) # add the integer to the result list return result def parse_phone_string( pn ) : """ Returns a three-element integer list for string phone # pn: 1st element: pn area code 2nd element: pn prefix 3rd element: pn line number """ # convert pn into a cleaned up string # strip() won't fully clean this string up, since we're looking to only get numbers out of this string # we'll do this by looking at each character cleaned_up_pn = "" # need to loop to process each character for ch in pn : if (ch in "0123456789" ) : # this will check if ch is a digit # we are only updating our accumulator if ch is a digit cleaned_up_pn = cleaned_up_pn + ch # when you set up looping with accumulation, make sure you're updating in the loop # no need for an else case because there's nothing to do if ch is not a numeric string # split cleaned up string into list # print( cleaned_up_pn ) # first 3 digits are area code, second 3 are prefix, remaining 4 are line number # area_code = cleaned_up_pn[ 0 ] + cleaned_up_pn[ 1 ] + cleaned_up_pn[ 2 ] area_code = cleaned_up_pn[ 0 : 3 ] # equivalent to line above - slicing operator prefix = cleaned_up_pn[ 3 : 6 ] # characters 3,4,5 line_number = cleaned_up_pn[ 6 : 10 ] # or cleaned_up_pn[ 6 : ] # ** once you have these numbers, you can put them together however you'd like to format them # as long as you're in the class, you can do whatever you want as long as you are producing the desired output ns = area_code + " " + prefix + " " + line_number # build a string to pass into our ints() function, defined above # separate by space because ints() uses split() to get a list to loop through # print( ns ) when we print ns, there are no quotes because it is not in a list # print( any_string ) will not have quotes, but print( [ "any_string" ] ) will print ["any_string"] result = ints( ns ) # we can (and should!) use functions to make problems easier # you could also just separately convert area_code, prefix, and line_number within this program, but it is # important to realize that functions can call other functions return result # algorithm brainstorming: # starting from a string of only numbers, pick off the first 3 numbers, then the next 3, then the final 4 # because we can handle a string of only numbers, think about how to get a string of only numbers # will we need a loop? how about conditions (if statements)? any useful constants we could define?