Lab 5, Part 3: Strings with For Loops
Handling strings

Table of some string operations:
symbol | operation | example |
---|---|---|
+ | concatenation |
str1 = 'I am ' str2 = 'your father ' darth = str1 + str2 yoda = str2 + str1 |
* | repetition | 'hee'*3 ==> 'heeheehee' |
[] | index | str2[5]==> 'f' |
[:] | slice | str2[2:5]==> 'ur ' |
in | in | 'dad' in str2 ==> False 'at' in str2 ==> True |
not in | not in | str1 not in str2 ==> True str1 not in darth ==> False |
A couple of handy string tips:
yourString[-1]
returns the last letter of a string, eg'hello'[-1] ==> 'o'
.lower()
returns a lowercase version of the given string, eg'HeLLo.lower() ==> 'hello'
Task 1. Writing string functions with loops
Continue writing your functions in your lab05.py
file.
-
Write a function called
getWordValue(word)
that takes in a word, and returns the value of the word using the following (made-up) rule: Each vowel (a,e,i,o,u) counts as 5 and each consonant counts as 1. You may ignore numbers and special characters for this function.-
Here's an
isVowel
function that you can use (or, you can write your own):def isVowel(s): """returns True if s is a vowel; false otherwise""" lowercaseS = s.lower() return lowercaseS in 'aeiou'
- Here are some test cases for your
getWordValue
function:print(getWordValue('hello')) ==> 13 print(getWordValue('I')) ==> 5 print(getWordValue('ouch')) ==> 12 print(getWordValue('WELLESLEY')) ==> 21 print(getWordValue('Go 123 Wellesley!!!!')) ==> 27
-
-
Write a function called
starify(word)
that takes in a word, and returns a new string with a*
after each letter in the original word. Hint: create a new string variable, initially empty, that will store the new string to be returned.print(starify('OMG')) ==> O*M*G* print(starify('wicked')) ==> w*i*c*k*e*d* print(starify('Starry')) ==> S*t*a*r*r*y*
- Write a function called
betterStarify(word)
that takes in a word, and returns a new string with a*
after each letter in the original word, but not after the last letter in the word.print(betterStarify('OMG')) ==> O*M*G print(betterStarify('wicked')) ==> w*i*c*k*e*d print(betterStarify('Starry')) ==> S*t*a*r*r*y
-
In this task, you'll write two functions.
Note that in the box below, you're given a predicate calledstarTime
that returnsTrue
twenty percent of the time andFalse
eighty percent of the time.
You can copy/paste thestarTime
predicate below into yourlab05.py
file:import random def starTime(): """returns True 20% of the time; False otherwise. Note: random.random() returns a random number between 0 and 1 """ return random.random() > 0.80
-
Write a fruitful function called
makeOneRow
that takes one parameterrowLength
, and returns a string with lengthrowLength
that is made up of stars (*
) and dashes (-
). When generating the row, you can use thestarTime
predicate so that 20% of the row is stars. For each spot in the row, use the predicatestarTime
: if it returnsTrue
, add a star to your row, otherwise, add a dash. Here are some sample invocations ofmakeOneRow
:print(makeOneRow(20)) ==> -*------*--*----**-- print(makeOneRow(20)) ==> ----*----*---------- print(makeOneRow(20)) ==> ---***-*--**------*- print(makeOneRow(20)) ==> *--**----*--**--*---
- Write another fruitful function called
starrySky
that takes two parameters:width
andheight
.starrySky
returns a string that contains a 'sky' that haswidth
andheight
dimensions and each row is created by a call tomakeOneRow
. The sky is built by adding each row and a newline character (\n
) at the end. Here are some sample invocations:print(starrySky(10, 10)) ==> *-------*- --*------- ---------- ---**----- **--*--*-- --------*- ---------- -----*---- ------*--- --*------- print(starrySky(5, 50)) ==> ----------------**-----**-*----------*---------*-- *--*----*---*---*-----**------*------------*--*--- -*---*---*--------*----------**--------*---*--*--- ---**----*-**---------**---*-------**--*-------*-- ------**-----------------*--------*-----*---*--*-- print(starrySky(3, 60)) ==> --------*-**-**---*---*---------*--*--**-------------------* ----*---------*--*-*--*-**---*----*--------*---*-*----*----*
-
- Write a predicate called
lottaVowels(word)
that returns True if the word contains more than 2 vowels. You may use the providedisVowel
in yourlab05.py
file.print(lottaVowels('OMG')) ==> False print(lottaVowels('hello')) ==> False print(lottaVowels('ABBA')) ==> False print(lottaVowels('GottaLOVEABBA')) ==> True print(lottaVowels('piano')) ==> True print(lottaVowels('eee')) ==> True print(lottaVowels('gummybears')) ==> True print(lottaVowels('laugh')) ==> False print(lottaVowels('laughingxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')) ==> True
Note: look at the last example, with this string 'laughingxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'. It would be efficient if your
lottaVowels
returned True as soon as the third vowel was encountered, rather than waiting until the end of the string. Can you amend yourlottaVowels
so it does that? (Sometimes we call this 'early exit')
- Write a function called
checkPassword(word)
that takes in a word, and returns True if the word satisfies the following password criteria and False otherwise. Hint: Python has some very useful built-in functions such asislower,isupper
andisdigit
, for example'a'.islower()
returnsTrue
and'a'.isupper()
returnsFalse
.- Password must contain a mix of upper and lower case letters
- Password must contain at least 1 number
- Password must contain at least 1 special character from this set !#$%&*
print(checkPassword('hello123')) ==> False print(checkPassword('PASSWORD')) ==> False print(checkPassword('myPASSWORD?')) ==> False print(checkPassword('loveMyDogCharlie!')) ==> False print(checkPassword('CS111#rocksmyworld')) ==> True print(checkPassword('running99*FAST')) ==> True print(checkPassword('oK8!')) ==> True # Minimum length would be good idea too
- [OPTIONAL] Write a function called
ransomNote(sentence)
that takes in a sentence, and returns a new sentence, based on the original sentence, with each letter randomly capitalized (with a 50% chance of being capitalized. Might need to use therandom.randint
function). Need arandint()
refresher? Here is an example from the previous lab with the coin flip, and here are the general python documentation pages for random numbers.print(ransom("Must provide chocolate to get your teddy bear back")) ==> muST ProvIDE CHocOlATe To get YOur TEddY bEAr bACK print(ransom("Meet me at grand central station with harry styles and a million dollars tonight")) ==> mEET mE at graND CentRAL sTatIOn WITh HarRY StYlEs AND a mIlLIOn DOLLaRs TOnigHT