› Forums › Web Development › HarvardX: CS50W – CS50’s Web Programming with Python and JavaScript › CS50W – Lecture 3 – Django › Understanding re.sub(r”\.md$”, “”, filename) in Real Projects
- This topic is empty.
-
AuthorPosts
-
March 28, 2026 at 7:39 am #6287
When you start building real applications—especially with frameworks like Django—you quickly move beyond theory into handling files, naming conventions, and clean data processing.
A great example of this comes from a typical “wiki” or “notes” project, where entries are stored as Markdown files (
.md) on disk.
🌍 The Real-World Context
Imagine you’re building a simple encyclopedia:
- Each article is stored as a file:
Python.md Django.md HTML.md - But when displaying entries to users, you don’t want:
Python.md ❌You want:
Python ✅
So the problem becomes:
👉 “How do we clean filenames before showing them to users?”
🔧 The Line of Code
re.sub(r"\.md$", "", filename)This is where the re module comes into play.
🧠 What This Line Actually Does
👉 It removes
.mdonly if it appears at the end of the filename.Example:
filename = "Python.md"After processing:
"Python"
🔍 Breaking It Down
Pattern:
r"\.md$"\.→ match a literal dot (.)md→ match"md"$→ match end of string
👉 So it matches exactly:
.mdat the end
Replacement:
""Replace the matched part with nothing
Function Meaning
re.sub(pattern, replacement, string)👉 “Find this pattern and remove it”
📊 Why This Matters (Practical Insight)
You might think:
“Why not just remove the last 3 characters?”
filename[:-3]But this is risky ❌
Problem:
filename = "notes.txt" filename[:-3] # → "notes."👉 That’s incorrect behavior.
✅ Why Regex Is Better
re.sub(r"\.md$", "", filename)✔ Removes
.mdonly when it’s actually there
✔ Leaves other filenames untouched
✔ Safer for real-world data
🧪 Real Examples
Filename Output Python.mdPythonnotes.mdnotesarchive.md.txtunchanged READMEunchanged
🧩 How It Fits in a Bigger Function
In a Django project, you might see something like:
return list(sorted( re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md") ))👉 This pipeline:
- Filters
.mdfiles - Cleans filenames
- Sorts them
- Returns a clean list
💡 Key Takeaway
This one line:
re.sub(r"\.md$", "", filename)is a small but powerful example of:
👉 Writing safe, production-ready code instead of shortcuts
🚀 Final Intuition
“Remove
.mdonly when it truly belongs there—at the end of the filename.”
- Each article is stored as a file:
-
AuthorPosts
- You must be logged in to reply to this topic.
