Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Detect Prompt Injection in Python
Implements a regex-based heuristic in Python to flag common prompt injection attempts before sending input to an LLM.
import re
def contains_prompt_injection(user_input: str) -> bool:
# Directives to ignore previous instructions or act as system
ignore_patterns = [
r"\bignore\s+(all\s+)?previous\s+instructions\b",
r"\bdisregard\s+(all\s+)?previous\s+instructions\b",
r"\bdon'?t\s+follow\s+(any\s+)?inst…
How to Estimate Token Count in Python
Estimates tokens in a text string using a whitespace and punctuation heuristic without external libraries.
def estimate_tokens(text: str) -> int:
"""Estimate token count using whitespace and punctuation heuristics."""
if not text:
return 0
words = text.split()
total_punctuation = sum(1 for char in text if char in ".,!?;:")
special_tokens = sum(1 for char in text if char in "\n\t")
# Rough …
How to Repair Malformed JSON Braces Heuristically in Python
Heuristically fix malformed JSON by balancing braces and quotes, using a stack-based approach to add missing closing characters.
import json
import re
def repair_json(text: str) -> str:
"""Heuristically repair malformed JSON by balancing braces and quotes."""
# Trim whitespace and handle leading/trailing garbage
text = text.strip()
# Remove common non-JSON decorations
text = re.sub(r'^(
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.