Lesson 47 of 55
9 mins readPython Global Substitution: string.gsub
In Plain English
`string.gsub(s, pattern, repl [, n])` replaces occurrences of `pattern` in `s`. The replacement can be a string, a lookup table, or a callback function.
Deep Dive: How It Works
String Replacement: `s:gsub("apple", "orange")`.
Table Replacement: `s:gsub("$(%w+)", table)` replaces variables using table key lookups.
Function Replacement: `s:gsub("(%w+)", func)` passes match to callback function.
Returns Pair: Returns the modified string and the total number of replacements made.
Core Rules to Remember

string.gsub Flexibility: Accepts string templates, hash lookup tables, or custom functions.

Replacement Count: Second return value gives total substitution count.
Live Interactive Example
Hit Run Code to see it liveTemplate Engine with string.gsub
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: gsub used the vars table to substitute $name, $app, and $status in one step.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Sanitize String with gsub
Declare `local str = "Hello-World-123"`.
Replace all hyphens with spaces: `local clean = str:gsub("-", " ")`.
Print `"Clean: " .. clean`.
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.