Skip to content

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?

python
catchphrase = "Captain America is here"
print(catchphrase[8:15])  # Output: America

Task

Extract "Captain" from catchphrase using slicing.

Answer
python
print(catchphrase[0:7])  # Output: Captain

Question: What happens if we omit the start or end index?

Example:

python
# 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.

python
reverse_name = "Doctor Strange"[::-1]
print(reverse_name)  # Output: egnartS rotcoD

Question: How can we extract every third character from a string?

Example:

python
message = "The Sorcerer Supreme"
print(message[::3])  # Output: T rceup

Reversing a String: The Mirror Dimension ↩ī¸ ​

Enter the mirror dimension by reversing strings.

python
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:

python
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.

python
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:

python
position = report.find("Thanos")
print(position)  # Output: -1

Task

Check if "mischief" is in report and find its position.

Answer
python
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.

python
identity = "Clark Kent"
secret_identity = identity.replace("Clark Kent", "Superman")
print(secret_identity)  # Output: Superman

Question: How can we replace multiple occurrences?

Example:

python
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.

python
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:

python
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.

python
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
python
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"

python
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
python
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.