String Slicing

STEP 4 โ€” String Slicing (a.k.a. Cutting Text Like a Ninja)

FINAL STEP OF UNIT 8, and this one is chefโ€™s kiss.

This is where strings stop being polite sentences and start becoming surgical tools.

Weโ€™re slicing, cutting, extracting, and analyzing text like coding ninjas.

Letโ€™s go.

Alright coder โ€” youโ€™ve created strings, combined them, and transformed them.

Now itโ€™s time to slice them.

String slicing lets you grab parts of a string:

  • first letter
  • last letter
  • a chunk in the middle
  • everything except the first few characters
  • everything after a certain point

This is HUGE for games โ€” especially for commands, names, and dialogue.


1. Basic Slice: string[start:end]

word = "dragon"
print(word[0:3])

You just sliced a dragon.

Respect.

Click Run

Output:

dra


2. Slice From the Start

word = "dragon"
print(word[:4])

Python assumes โ€œstart at the beginning.โ€

Click Run

Output:

drag


3. Slice to the End

word = "dragon"
print(word[2:])

Perfect for trimming prefixes.

Click Run

Output:

agon


4. Negative Indexing (Backwards Magic)

Negative numbers count from the end.

word = "dragon"
print(word[-3:])

Your slicing powers now work from both directions.

Click Run

Output:

gon


5. Why Slicing Matters for Games

String slicing lets you:

  • detect commands like “attack goblin”
  • extract player initials
  • shorten long item names
  • build UI previews
  • trim story text
  • analyze user input

This is where your game becomes interactive.


6. Example: Command Parsing

command = "attack goblin"

action = command[:6]
target = command[7:]

print("Action:", action)
print("Target:", target)

Your game now understands commands like a mini-AI.

Click Run

Mini Challenge

Take the string “Golden Sword”
Slice out “Sword” using slicing.

Modify and Run

Boom.

You extracted the weapon like a pro.

You now know how to:

  • slice strings
  • extract text
  • trim prefixes and suffixes
  • analyze commands
  • build interactive text systems