Working with Strings and Conditionals

Here is our plan for today:

No code to download for today -- you'll be writing everything from scratch. Create a lab3 folder and put all your code for today in that folder. Change your working directory to be the yourname_lab3 folder.

How to take apart and put together strings

It's useful to know how to extract parts of strings. First, let's set up some string variables (you can type these directly into your Canopy interactive window -- it's better to type than to copy and paste because the indentation will generate errors). Or you can copy them with your mouse and paste them into a file, and then run the file.
   theTruth = 'CS111 rocks my world!'
   name = 'Iggy Azalea'
   line1 = 'I\'m so fancy'  # note the backslash 
   line2 = 'You already know'
   line3 = 'I\'m in the fast lane'  # note the backslash 
   line4 = 'From LA to Tokyo'
Note: does it matter if you use single quotes (') or double quotes (") in python around strings? Short answer: no. Click here for a long explanation.
Now, try out these python commands and see what you get:
   theTruth[0]
   name[0]
   name[1:5]
   name[8:10]
   len(line2)
   line1*3
Note that we use the built-in python function len in the examples above. Here is a list of all the built-in python functions.
Let's get a little bit tricker with our string examples:
   name[-1]
   name[-3]
   line1[::-1]
   line3[::-5]
   line2*-1
   line4[len(line4)]
   line4[len(line4)-1]

Here are some special python string operators:
symbol operation example
+ concatenation str1 = 'I am '
str2 = 'your father '
darth = str1 + str2
yoda = str2 + str1
* repetition 'hee'*3 ==> 'heeheehee'
[] slicestr2[5]==> 'f'
[:] range str2[2:5]==> 'ur '
in in'leia' in str2 ==> False
'fat' in str2 ==> True
not in not instr1 not in str2 ==> True
str1 not in darth ==> False

Task 1. Writing simple string functions

Create a new file called lab3.py. You may, if you like, use the built-in Python function len(s), which returns the length of a string s. Copy and paste the function definitions template below into your lab3.py file. You'll need to fill in the missing code to make sure that your code works correctly.
Note that each function should be just one line of code.

def first(s):
    """returns the first letter of the given string
    e.g. first("tahoe") => t"""
    # ____________________
    # replace the blank line above with your code

def last(s):
    """returns the last letter of the given string
    e.g. last("tahoe") => e"""
    # ____________________
    # replace the blank line above with your code

def sameLength (s1, s2):
    """determines whether strings s1 and s2 have the same length
     e.g. sameLength("tahoe","snow") => False
     e.g. sameLength("cold","snow") => True"""
    # ____________________
    # replace the blank line above with your code

def average(a,b):
    """returns the average of two numbers
    e.g. average(9,12) => 10.5"""
    # ____________________
    # replace the blank line above with your code

		

Task 2. Writing more complex predicates

In this task, you'll write the following three string predicates (include them in your lab3.py file):
  1. isBookend(s): A string is a bookend if it begins and ends with the same letter. For example, "neon" is a bookend and "cake" is not a bookend.
  2. siblings(s1,s2): Two strings are siblings if For example, "Emily" and "Elise" and siblings; "Tucker" and "Oliver" are siblings, but "Sam" and "Scott" are not and "hi" and "hawaii" are not.
  3. stringAverage(s1,s2,s3): Checks to see if the middle string has a length that is the average of the other two strings. For example, "bowling" has a length that is the average of the length of the strings "football" and "soccer".
Write the predicates one at a time, testing each one to convince yourself that it works before moving on to the next one.

Task 3: Text analysis

In this task, you will write python functions to analyze a given text.

Here are some examples:

"I love you"
  3 words in your text.
  8 chars in your text.
  Most common vowel in your text is "o"
................
"May the odds be ever in your favor"
  8 words in your text.
  27 chars in your text.
  Most common vowel in your text is "e"
................
"Be yourself; everyone else is already taken"
  7 words in your text.
  37 chars in your text.
  Most common vowel in your text is "e"
................
"Here's to the crazy ones. The misfits. The rebels. The troublemakers. The 
round pegs in the square holes. The ones who see things differently. They're
not fond of rules. And they have no respect for the status quo. You can 
quote them, disagree with them, glorify or vilify them. About the only 
thing you can't do is ignore them. Because they change things. They push 
the human race forward. And while some may see them as the crazy ones, we 
see genius. Because the people who are crazy enough to think they can change
the world, are the ones who do"
  101 words in your text.
  448 chars in your text.
  Most common vowel in your text is "e"
................
"YYYYYYY"
  1 words in your text.
  7 chars in your text.
  Most common vowel in your text is "No vowels present."
................

You need to write one function, say analyzeText(text), that will analyze the given text and print the information shown above. Namely, the number of words and the number of characters in the text are counted and the most common vowel is printed. If there are no vowels, then that is reported. The text is a parameter to the analyzeText(text) function. Note that spaces do not count as characters. For counting the words, split() might come in handy.

In this task, you have the freedom to structure your solution as you see best. If you would like some guidance, you can follow the steps below.

One suggested strategy

Step 1. letterCount(text,letter)
letterCount(text,letter) counts the number of occurences of the given letter in the text. You can use python's count() function. Examples:
letterCount("hello there","e") returns 3
letterCount("oh my goodness","e") returns 1
letterCount("oh my goodness","o") returns 3
letterCount("oh my goodness","a") returns 0

Step 2. maxVowelCount(text)
maxVowelCount(text) returns the vowel with the most occurences in the given text. This function uses letterCount. Here is an example:
maxVowelCount("hello there") returns "e"
maxVowelCount("oh my goodness") returns "o"
maxVowelCount("CS111") returns "No vowels present"

Step 3. analyzeText(text)
You might find some of the built-in python functions useful, as well as python's string functions.
text1 = "I love you"
analyzeText(text1)
produces
"I love you"
  3 words in your text.
  8 chars in your text.
  Most common vowel in your text is "o"
text2 = "May the odds be ever in your favor"
analyzeText(text2)
produces
"May the odds be ever in your favor"
  8 words in your text.
  27 chars in your text.
  Most common vowel in your text is "e"
(see large pink box above for more examples).

Note that the analyzeText() function requires a string parameter. Later on this semester, you will learn how to write python code to read an entire file. For example, you'll learn how to write programs that, given the name of the file, will open and read all the lines in a file and analyze them.