Additional String stuff

There are more uses for the word "in" in Python:

  1. We are now used to doing iteration using the pattern:  for fred in range(something): where fred is a variable that will be given the values: (0, 1, 2, ... , something-1), one at a time.

  2. A new, but similar type of iteration:  for harry in 'abcdef':  where harry is a variable that will be given the values: ('a', 'b', 'c', 'd', 'e', and 'f'), one at a time.  Of course, 'abcdef' can be replaced by a variable containing a string.  So, for instance:

  3. >>> bleep = 'dwurp'
    >>> for Q in bleep:
      print Q
    d
    w
    u
    r
    p
  4. Yet another use of 'in' is to check whether a string is embedded inside another, or not.  For instance: if   'Harry'  in  'Friends of Harry Potter': So, the expression A in B returns True if the string in A is anywhere inside the string in B, otherwise False.  This use of in doesn't tell you where the string A is, or even how often it appears inside B, just whether it's there or not.

Exercises:

Use the in keyword in the following exercises (do not use while and do not use range()):

1. Create the function countChars(s,c) that is given a string in s, and a character in c, and counts how many times c appears inside s.  Example:

countChars('abcab','b')  # returns 2

2. Create the function howManyOfAinB(alphabet,s) which returns the number of distinct letters in alphabet that happen to occur inside the string s.  Example:

howManyOfAinB('aeiou','on the other hand')  # returns 3 because only 'a', 'e' and 'o' appear inside the string

3. Challenge: create the function countStrings(s,substring) that counts how many times substring appears inside s.  However, you may not use any of the string methods (like .find()), and you must step through the string character-by-character using for c in s:  Example:

countStrings('on the other hand','the')  # returns 2