Lesson 43 of 55
8 mins readPython The string Library: sub, byte, rep & Case
In Plain English
The built-in `string` library provides functions for slicing, byte conversions, case normalization, and formatting. Functions can be called as `string.fn(s)` or via method syntax `s:fn()`.
Deep Dive: How It Works
Method Calling Syntax: All strings have a metatable with `__index = string`, enabling `"hello":upper()`.
string.sub(s, start, end): Extracts substring using 1-based indices (supports negative indices).
string.rep(s, n): Repeats string `n` times.
string.byte / string.char: Converts between characters and ASCII/Unicode byte codes.
Core Rules to Remember

String Method Syntax: Call `s:upper()` or `s:sub(1, 4)` directly on any string.

Negative Indexing: `s:sub(-3)` extracts the last 3 characters.
Live Interactive Example
Hit Run Code to see it liveString Transformations
Python 3.12
1
2
3
4
5
6
7
Output Console
Click "Run Code" to view the rendered output.
How it works: text:sub pulled slices and string.rep repeated the divider line.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Extract Substring Prefix
Declare `local code = "PROD-9874"`.
Extract the first 4 characters `local env = code:sub(1, 4)`.
Print `"Environment: " .. env`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.