Advanced String Manipulation â
Dive deeper into string slicing, reversing, and advanced manipulations, much like superheroes decoding complex messages.
Slicing Operator: Decoding Secret Messages đĒ â
Superheroes often decode secret messages by extracting parts of codes.
Question: How can we extract "America" from catchphrase
?
catchphrase = "Captain America is here"
print(catchphrase[8:15]) # Output: America
Task
Extract "Captain" from catchphrase
using slicing.
Answer
print(catchphrase[0:7]) # Output: Captain
Question: What happens if we omit the start or end index?
Example:
# Omitting start index
print(catchphrase[:7]) # Output: Captain
# Omitting end index
print(catchphrase[8:]) # Output: America is here
Advanced Slicing: Time Manipulation đ â
Just as some heroes manipulate time, we can manipulate strings with advanced slicing.
reverse_name = "Doctor Strange"[::-1]
print(reverse_name) # Output: egnartS rotcoD
Question: How can we extract every third character from a string?
Example:
message = "The Sorcerer Supreme"
print(message[::3]) # Output: T rceup
Reversing a String: The Mirror Dimension âŠī¸ â
Enter the mirror dimension by reversing strings.
mirror_message = "emit fo elbbub"
original = mirror_message[::-1]
print(original) # Output: bubble of time
Question: Can we reverse only a portion of a string?
Example:
phrase = "Time Stone"
reversed_part = phrase[:4][::-1] + phrase[4:]
print(reversed_part) # Output: emiT Stone
Finding Substrings: Locating the Villain đ â
Just as heroes search for villains, we can search for substrings.
report = "Loki spotted in Asgard, Loki causing mischief"
position = report.find("Loki")
print(position) # Output: 0
Question: What if the substring is not found?
Example:
position = report.find("Thanos")
print(position) # Output: -1
Task
Check if "mischief" is in report
and find its position.
Answer
if "mischief" in report:
position = report.find("mischief")
print(f"'mischief' found at position {position}")
# Output: 'mischief' found at position 35
Immutable Strings and Replacement: Disguises đ¸ â
Heroes often disguise themselves; similarly, we can create new strings with replacements.
identity = "Clark Kent"
secret_identity = identity.replace("Clark Kent", "Superman")
print(secret_identity) # Output: Superman
Question: How can we replace multiple occurrences?
Example:
message = "Flash is fast, Flash is quick"
new_message = message.replace("Flash", "Barry")
print(new_message) # Output: Barry is fast, Barry is quick
Start and End Checks: Patrol Duty đ â
Determine if a patrol starts or ends at a specific location.
patrol_route = "Begin at Daily Planet, end at Fortress of Solitude"
starts_at = patrol_route.startswith("Begin")
ends_at = patrol_route.endswith("Solitude")
print(f"Starts at Daily Planet: {starts_at}, Ends at Fortress of Solitude: {ends_at}")
# Output: Starts at Daily Planet: True, Ends at Fortress of Solitude: True
Question: How can we check for case-insensitive starts or ends?
Example:
starts_at = patrol_route.lower().startswith("begin")
ends_at = patrol_route.lower().endswith("solitude")
The .split()
Spell: Decoding Transmissions đŦī¸đ â
Transform encrypted messages into readable format.
transmission = "hero:Batman;ally:Robin;location:Gotham"
details = transmission.split(';')
for detail in details:
key, value = detail.split(':')
print(f"{key.capitalize()}: {value}")
# Output:
# Hero: Batman
# Ally: Robin
# Location: Gotham
Task
Given coordinates = "x=45|y=90|z=120"
, extract the values of x, y, and z.
Answer
coords = coordinates.split('|')
for coord in coords:
axis, value = coord.split('=')
print(f"{axis.upper()}: {value}")
# Output:
# X: 45
# Y: 90
# Z: 120
Correcting a Scrambled Message đ â
Help the heroes unscramble a vital message.
Task
Unscramble the sentence: "justice for fight we"
scrambled = "justice for fight we"
words = scrambled.split()
unscrambled = " ".join(words[::-1])
print(unscrambled)
# Output: we fight for justice
Question: How can we capitalize the first letter of the unscrambled sentence?
Answer
unscrambled = unscrambled.capitalize()
print(unscrambled)
# Output: We fight for justice
Conclusion â
By mastering advanced string manipulation, you've enhanced your ability to decode and transform data, much like a superhero deciphering critical information. Keep practicing these techniques to become a string manipulation expert.