# stringfun.py # Walker M. White (wmw2) # October 15, 2015 """A module of recursive functions on Strings.""" import string # constants to help with string import sys # Allow us to go really deep sys.setrecursionlimit(999999999) def length(s): """Returns: number of characters in s Parameter: s the string to measure Precondition s is a string""" assert type(s) == str, str(s) + ' is not a string' # get in the habit # s is empty if s == '': return 0 # s has at least one character # return (length of s[0]) + (length of s[1:]) return 1 + length(s[1:]) def num_e(s): """Returns: number of 'e's in s Parameter: s the string to count Precondition s is a string""" assert type(s) == str, str(s) + ' is not a string' # get in the habit # s is empty if s == '': return 0 # s has at least one character # return (number of 'e's in s[0]) + (number of 'e's in s[1:]) if s[0] == 'e': first = 1 else: first = 0 return first+num_e(s[1:]) def deblank(s): """Returns: s but with blanks removed Parameter: s the string to edit Precondition s is a string""" assert type(s) == str, str(s) + ' is not a string' # get in the habit # s is empty if s == '': return s # Remove first whitespace if s[0] in string.whitespace: return deblank(s[1:]) # Keep first character, but remove later whitespace return s[0] + deblank(s[1:]); def depunct(s): """Returns: s but with everything that is not a letter removed Parameter: s the string to edit Precondition s is a string""" assert type(s) == str, str(s) + ' is not a string' # get in the habit # s is empty if s == '': return s if not s[0] in string.letters: return depunct(s[1:]) return s[0] + depunct(s[1:]); def reverse(s): """Returns: s with its characters in reverse order Parameter: s the string to reverse Precondition s is a string""" assert type(s) == str, str(s) + ' is not a string' # get in the habit if s == '': return s # s has at least 2 chars return reverse(s[1:]) + s[0]