Rhea Rajashekhar P4 Popcorn Hacks 3.4 strings
# Python Popcorn Hack 1: Get the lyrics of a clean song
# Step 1: Lyrics of a new clean song
lyrics = """
Under the bright lights, we shine, we glow
Together, we’re unstoppable, let’s go
Through the highs and the lows
We’ll never be alone, no, we’ll never be alone
When the world turns its back, we stand tall
We’ll break the silence, hear our call
No matter what they say, we’ll rise above
United by a love that’s strong enough
We are unbreakable, untouchable
Together, we’re invincible
We are unbreakable, unstoppable
Together, we’re incredible
Through the storm, we’ll find our way
In the dark, we’ll light the day
No one can take this away
Our bond is here to stay
We are unbreakable, untouchable
Together, we’re invincible
We are unbreakable, unstoppable
Together, we’re incredible
"""
# The song title
song_title = "unbreakable"
# Step 2: Find how many times the title appears in the lyrics
title_count = lyrics.lower().count(song_title.lower())
print(f'The title "{song_title}" appears {title_count} times in the song.')
# Step 3: Find the index of the 50th word
words = lyrics.split() # Split lyrics into words
if len(words) >= 50:
word_50th = words[49] # Words are zero-indexed, so 50th word is at index 49
index_of_50th = lyrics.index(word_50th)
print(f'The index of the 50th word ("{word_50th}") is: {index_of_50th}')
else:
print("The lyrics have less than 50 words.")
# Step 4: Replace the first verse with the last verse
verses = lyrics.strip().split("\n") # Split the lyrics into verses
if len(verses) >= 2:
first_verse = verses[0]
last_verse = verses[-1]
# Replace the first verse with the last one
new_lyrics = lyrics.replace(first_verse, last_verse, 1)
print("\nLyrics after swapping the first and last verse:")
print(new_lyrics)
else:
print("The lyrics do not have enough verses to perform a swap.")
# Step 5: Concatenate two verses together to create your own song
if len(verses) >= 3:
new_song = verses[1] + "\n" + verses[2] # Concatenating the second and third verses
print("\nNew song created by concatenating two verses:")
print(new_song)
else:
print("The lyrics do not have enough verses to concatenate.")
%% js
// Popcorn Hack 2: Concatenate a flower with an animal to create a new creature
// Step 1: Define a flower and an animal
const flower = "Rose";
const animal = "Tiger";
%% js
// Step 2: Concatenate to make a new creature using template literals
let newCreature = `${flower} ${animal}`;
console.log("The new creature is: " + newCreature);
%% js
// Step 3: Write a short story about the creature using variables and dialog
let name = "Tyler"; // New creature's name
let color = "crimson";
let habitat = "the enchanted jungle";
let story = `${name} was a rare creature with petals as soft as silk, but claws sharp enough to tear through steel.
One evening, as the sun set in ${habitat}, ${name} roared, its ${color} fur glowing in the twilight.
"Why does the world fear me?" ${name} whispered to the stars, staring at the night sky.
A wise owl swooped down and replied, "They fear what they don't understand, ${name}. But your beauty is undeniable."
With a sigh, ${name} said, 'Maybe one day, they’ll see me for who I am, not for the fearsome stories they’ve heard.'`;
console.log(story);
# Main strings hack
def analyze_text():
# User input
text = input("Enter a sentence or multiple sentences: ")
# Original string
print(f"\nOriginal string: {text}")
# Total characters (including spaces)
total_characters = len(text)
print(f"Total characters (including spaces): {total_characters}")
# Finding longest word and its length
words = re.findall(r'\b\w+\b', text) # Using regex to exclude punctuation
longest_word = max(words, key=len)
print(f"Longest word: {longest_word} ({len(longest_word)} characters)")
# Reversed string
reversed_string = text[::-1]
print(f"Reversed string: {reversed_string}")
# Middle word/character (excluding spaces and special characters)
cleaned_text = ''.join(re.findall(r'\w+', text)) # Removes special characters and spaces
middle_index = len(cleaned_text) // 2
if len(cleaned_text) % 2 == 0:
middle_character = cleaned_text[middle_index - 1:middle_index + 1]
else:
middle_character = cleaned_text[middle_index]
print(f"Middle character(s) (excluding spaces/special characters): {middle_character}")
# Custom function: Replace word feature
original_text = text
word_to_replace = input("\nEnter the word you want to replace: ")
replacement_word = input("Enter the new word: ")
if word_to_replace in original_text:
updated_text = original_text.replace(word_to_replace, replacement_word)
print(f"Updated string: {updated_text}")
else:
print(f"The word '{word_to_replace}' is not in the original string!")
# Call the function to run the analyzer
analyze_text()
%% js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Analyzer</title>
</head>
<body>
<h1>Text Analyzer</h1>
<textarea id="inputText" rows="4" cols="50" placeholder="Enter your text here..."></textarea><br>
<button onclick="analyzeText()">Analyze</button><br><br>
<p id="originalText"></p>
<p id="totalCharacters"></p>
<p id="longestWord"></p>
<p id="reversedText"></p>
<p id="middleCharacter"></p>
<script>
function analyzeText() {
let text = document.getElementById("inputText").value;
// Display original text
document.getElementById("originalText").innerHTML = `Original string: ${text}`;
// Total characters including spaces
let totalCharacters = text.length;
document.getElementById("totalCharacters").innerHTML = `Total characters (including spaces): ${totalCharacters}`;
// Finding longest word
let words = text.match(/\b\w+\b/g);
let longestWord = words.reduce((longest, current) => current.length > longest.length ? current : longest, "");
document.getElementById("longestWord").innerHTML = `Longest word: ${longestWord} (${longestWord.length} characters)`;
// Reversed string
let reversedText = text.split('').reverse().join('');
document.getElementById("reversedText").innerHTML = `Reversed string: ${reversedText}`;
// Middle character/word (excluding spaces and special characters)
let cleanedText = text.replace(/[^A-Za-z0-9]/g, ''); // Removing spaces and special characters
let middleIndex = Math.floor(cleanedText.length / 2);
let middleCharacter = cleanedText.length % 2 === 0
? cleanedText[middleIndex - 1] + cleanedText[middleIndex]
: cleanedText[middleIndex];
document.getElementById("middleCharacter").innerHTML = `Middle character(s): ${middleCharacter}`;
}
</script>
</body>
</html>
Optional Word Replacement Feature (JavaScript)
To add the word replacement functionality to the JavaScript version, you can extend the script as follows:
html
Copy code
<p>Replace a word:</p>
<input id="wordToReplace" placeholder="Word to replace">
<input id="replacementWord" placeholder="Replacement word">
<button onclick="replaceWord()">Replace Word</button>
<p id="updatedText"></p>
<script>
function replaceWord() {
let text = document.getElementById("inputText").value;
let wordToReplace = document.getElementById("wordToReplace").value;
let replacementWord = document.getElementById("replacementWord").value;
if (text.includes(wordToReplace)) {
let updatedText = text.replaceAll(wordToReplace, replacementWord);
document.getElementById("updatedText").innerHTML = `Updated string: ${updatedText}`;
} else {
document.getElementById("updatedText").innerHTML = `The word '${wordToReplace}' is not in the original string!`;
}
}
</script>