String Slicing
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.
Output:
dra
2. Slice From the Start
word = "dragon"
print(word[:4])
Python assumes โstart at the beginning.โ
Output:
drag
3. Slice to the End
word = "dragon"
print(word[2:])
Perfect for trimming prefixes.
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.
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.
Mini Challenge
Take the string “Golden Sword”
Slice out “Sword” using slicing.
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


