Fall 2024 - P2
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.4 Strings
Added Popcorn Hacks
Popcorn Hack #1
Define three variables: Movie, Sport, Pet name
Combine these variables into the following message: Hello, my favorite movie is [Movie]. My favorite sport is [Sport] and my pet’s name is [petName].
Do this exercise using both concatenation and interpolation
%%js
let favoriteMovie = "Inception";
let favoriteSport = "soccer";
let petName = "Buddy";
// Concatenation
let concatenatedMessage = "My favorite movie is " + favoriteMovie + ". I love playing " + favoriteSport + " and my pet's name is " + petName + ".";
// Interpolation
let interpolatedMessage = `My favorite movie is ${favoriteMovie}. I love playing ${favoriteSport} and my pet's name is ${petName}.`;
<IPython.core.display.Javascript object>
Popcorn Hack #2
You are given a string “A journey of a thousand miles begins with a single step”. Your task is to write code that uses the slice() method to:
- Extract the word “journey”
- Extract the word “miles” using a negative starting index
- Extract everything from the word “begins” to the end of the sentence
- Output these extractions at the end of the code
%%js
// Define string
let phrase = "A journey of a thousand miles begins with a single step";
// Extraction
let partOne = phrase.slice(2, 8);
let partTwo = phrase.slice(-18, -12);
let remainder = phrase.slice(20);
// Output
console.log(partOne); // Output: journey
console.log(partTwo); // Output: miles
console.log(remainder); // Output: begins with a single step
Popcorn Hack #3 Removing Vowels
Write a function that takes a sentence as input and removes all the vowels (a, e, i, o, u) from it, both uppercase and lowercase. The program should return the modified sentence.
Instructions:
Use a loop or list comprehension to filter out vowels. Test it with sentences that contain both uppercase and lowercase vowels.
def remove_vowels(input_str):
vowels = "aeiouAEIOU"
result = ''.join([char for char in input_str if char not in vowels])
return result
sentence = "I enjoy learning Python!"
print(remove_vowels(sentence))
njy lrnng Pythn!
Reverse Order Hack
Take a sentence as input, then reverse the order of words, but not the characters within the words.
Instructions:
Split the sentence into words, reverse the word list, and then join them back into a string. Try this with different sentences!
def reverse_words(input_str):
words = input_str.split()
reversed_words = " ".join(words[::-1])
return reversed_words
sentence = "I love coding!"
print(reverse_words(sentence))
coding! love I