# Some string functions worked out # ========================================================== # findLetter(A,B) -- A is a string, and B is a one-character string (a letter) # findLetter will return the first (left-most) position inside A where B can be found # or return -1 if B cannot be found inside A # findLetter('fish','f') -> 0 # findLetter('fish','F') -> -1 # findLetter('fish','h') -> 3 def findLetter(original,letter): i = 0 while i < len(original): if original[i] == letter: return i i = i + 1 return -1 # the while loop has been exhausted, letter not found # ========================================================== # isVowel(A) -- A is a letter (one-character string) # returns True if A is a vowel (upper- or lower-case 'a','e','i','o', or 'u') # returns False if A is anything else # isVowel('a') -> True # isVowel('E') -> True # isVowel('R') -> False # isVowel('+') -> False def isVowel_1(c): if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u': return True if c == 'A' or c == 'E' or c == 'I' or c == 'O' or c == 'U': return True return False # or, more easily... def isVowel_2(c): vowels = 'aeioAEIOU' if findLetter(vowels,c) >= 0: return True return False # or even shorter... def isVowel_3(c): return findLetter('aeioAEIOU',c) >= 0 # ========================================================== # copyStringBackwards(s) -- returns the same string as s, but backwards # copyStringBackwards('abCD') -> 'DCba' # this supposes that we don't already know how to do this with string-slicing def copyStringBackwards(s): answer = '' i = len(s) - 1 while i >= 0: answer = answer + s[i] i = i - 1 return answer # ============================================================ # findWord(Original,Word) -- Original and Word are strings (of any length) # return the left-most position of Word inside Original # return -1 if Word cannot be found inside Original # findWord('salad','x') -> -1 # findWord('fishy','shy') -> 2 # findWord('fish','fi') -> 0 # findWord('fish','FI') -> -1 def findWord(original,word): i = 0 # on the next line... # if word is longer than one character, we can do: while i < len(original) - len(word) + 1 # but while i < len(original) also works, but is more wasteful of machine time while i < len(original): if original[i:i+len(word)] == word: return i i = i + 1 return -1