Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Automatically Detect Weak Passwords from Large Password Lists in Python
This Python script identifies weak passwords from a list by checking length, common patterns, sequential characters, and uniform characters, returning those that fail the security checks.
import re
COMMON_PASSWORDS_FILE = "common_passwords.txt"
def is_weak(password):
# Check length
if len(password) < 8:
return True
# Check for common patterns
if password.lower() in {"password", "123456", "qwerty", "letmein", "admin", "welcome"}:
return True
# Check for sequential c…
Build a Secure Password Strength Checker in Python
A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.
import re
def password_strength(password: str) -> str:
score = 0
if len(password) >= 8:
score += 1
if re.search(r'[a-z]', password):
score += 1
if re.search(r'[A-Z]', password):
score += 1
if re.search(r'\d', password):
score += 1
if re.search(r'[!@#$%^&*(),.?":…
Count Characters, Words, and Lines in Python Text
Counts characters, words, lines, and the most common words in a given string using Python's standard library.
from collections import Counter
def count_data(text):
"""Count characters, words, lines, and most common words in text."""
char_count = len(text)
word_count = len(text.split())
line_count = text.count("\n") + 1
word_freq = Counter(text.lower().split())
most_common = word_freq.most_common(3)
…
Extract Data from Strings in Python: Beginner's Guide
A beginner-friendly helper that splits a comma-separated string into a list, shows word count, and extracts the first and last words using Python's split() and join() methods.
text = "python,string,extract,beginner"
words = text.split(",")
print("Full text:", text)
print("Word count:", len(words))
print("First word:", words[0])
print("Last word:", words[-1])
joined = " | ".join(words)
print("Joined with separator:", joined)
Find Data From a String in Python: Stats, Clean, Keywords
Three helper functions for beginners: compute character/word/sentence stats, normalize whitespace and case, and extract unique sorted keywords from a string.
def get_text_stats(text):
"""Return basic statistics about a string."""
words = text.split()
sentences = text.replace('!', '.').replace('?', '.').split('.')
sentences = [s for s in sentences if s.strip()]
return {
'characters': len(text),
'words': len(words),
'sentences': le…
Find the Longest Word in a Sentence in Python
Splits a sentence into words and returns the longest one using the built-in max() function with len as the key.
def find_longest_word(sentence: str) -> str:
words = sentence.split()
if not words:
return ""
return max(words, key=len)
if __name__ == "__main__":
test_sentence = "The quick brown fox jumps over the lazy dog"
longest = find_longest_word(test_sentence)
print(f"Longest word: '{longest}'…
How to Build a Basic Text Processor in Python
Split text into sentences, count words, find the longest word, and convert text to uppercase — all with pure Python string methods.
text = """The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!"""
sentences = text.split(". ")
word_count = 0
longest_word = ""
for sentence in sentences:
words = sentence.split()
word_count += len(words)
for word in words:
clea…
How to Build a Text Processor in Python
This code defines functions to count words, sentences, and find the longest word in a text, then prints basic statistics like uppercase and lowercase versions.
def count_words(text):
return len(text.split())
def count_sentences(text):
sentence_endings = ".!?"
count = 0
for char in text:
if char in sentence_endings:
count += 1
return count
def longest_word(text):
words = text.split()
if not words:
return ""
retur…
How to Capitalize First Letter of Each Word in Python
Capitalizes the first letter of every word in a string using the built-in title() method.
def capitalize_words(text):
return text.title()
if __name__ == "__main__":
sample = "hello world from python"
result = capitalize_words(sample)
print(result)
How to Convert snake_case to Title Case in Python
Convert snake_case strings to title case by splitting on underscores, capitalizing each word, and joining them with spaces.
def to_title_case(snake_str):
words = snake_str.split("_")
return " ".join(word.capitalize() for word in words)
if __name__ == "__main__":
examples = ["hello_world", "convert_snake_case", "already_title_case", "multiple__under_scores"]
for example in examples:
print(f"{example!r:35} -> {to_tit…
How to Count Words in a String in Python
Split a paragraph on whitespace and return the number of words using Python's built-in string methods.
def count_words(paragraph: str) -> int:
words = paragraph.split()
return len(words)
if __name__ == "__main__":
paragraph = "The quick brown fox jumps over the lazy dog."
result = count_words(paragraph)
print(f"Word count: {result}")
How to Filter a List of Strings by Keyword in Python
A helper function filters a list of strings by a keyword search with optional case sensitivity.
def filter_strings(items, keyword, case_sensitive=False):
"""
Filter a list of strings by a keyword.
Args:
items: list of strings to filter
keyword: substring to search for
case_sensitive: if True, match case exactly
Returns:
list of strings containing the keyw…
How to Format Text in Python (Beginner's Guide)
This beginner-friendly Python script demonstrates text formatting basics: stripping whitespace, converting to title case, replacing substrings, splitting into words, and generating a snippet.
text = " hello world, welcome to python skillset! "
cleaned = text.strip()
title_cased = cleaned.title()
replaced = title_cased.replace("Python", "PYTHON")
words = replaced.split()
word_count = len(words)
first_three = " ".join(words[:3])
snippet = first_three + "..."
print("Original:", repr(text))
print("Stripped:"…
How to Generate Initials from a Full Name in Python
Extract and uppercase the first letter of each word in a full name to produce initials using standard string methods.
def generate_initials(full_name):
parts = full_name.strip().split()
initials = ''.join(part[0].upper() for part in parts if part)
return initials
if __name__ == "__main__":
name = "john f. kennedy"
print(generate_initials(name))
How to Inspect String Statistics in Python
A beginner-friendly function that returns detailed statistics about a string, including length, word count, character types, and easy text transformations.
def inspect_text(text: str) -> dict:
"""Return useful stats about a string for beginners."""
words = text.split()
return {
"length": len(text),
"word_count": len(words),
"uppercase": sum(1 for ch in text if ch.isupper()),
"lowercase": sum(1 for ch in text if ch.islower()),
…
How to Join List of Words into a Sentence in Python
Concatenate a list of strings into a single sentence with spaces using the Python string join() method.
words = ["Hello", "world", "this", "is", "Python"]
sentence = " ".join(words)
print(sentence)
How to Parse and Clean Text in Python
This code defines three helper functions to parse text into lowercase words, count unique word frequencies, and clean text by removing punctuation and extra whitespace.
def extract_words(text: str) -> list[str]:
"""Return a list of lowercase words from the given text."""
return [word.lower() for word in text.split() if word.isalpha()]
def count_unique_words(text: str) -> dict[str, int]:
"""Return a dictionary with unique words and their frequencies."""
words = extra…
How to Process Lines of Text in Python
Strip whitespace, split a multi-line string, count words per line, and print structured summaries using basic string methods and loops.
text = """ Python is great!
Coding is fun.
Python skills help you grow. """
lines = text.strip().splitlines()
line_count = len(lines)
processed = []
for line in lines:
stripped = line.strip()
word_count = len(stripped.split())
processed.append({
"original": line,
"stripped": stripp…
How to Process Text in Python
This code processes multiline text by splitting lines, stripping whitespace, counting words and characters, and converting to lowercase.
def process_text(text):
lines = text.split("\n")
clean_lines = []
for line in lines:
stripped = line.strip()
if stripped:
tokens = stripped.split()
title_case = stripped.lower()
clean_lines.append({
"raw": stripped,
"word_c…
How to Process Text in Python: Normalize Whitespace and Count Words
A beginner-friendly function that normalizes whitespace in a string and counts total and unique words using Python's standard library.
def process_text(text):
"""Basic text processing: normalize whitespace and count words."""
normalized = " ".join(text.split())
word_count = len(normalized.split())
char_count = len(normalized)
# Count unique words
unique_words = set(normalized.lower().split())
unique_count = len(unique…
How to Sort Text Alphabetically in Python
Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.
def sort_words(text):
"""Sort words alphabetically (case-insensitive), preserving case."""
words = text.split()
return sorted(words, key=str.lower)
def sort_lines(text):
"""Sort lines alphabetically (case-insensitive), preserving case."""
lines = [line for line in text.splitlines() if line.strip(…
How to Sort Text in Python with a Simple Helper Function
A compact helper function that sorts a list of strings or splits a string into words and sorts them alphabetically, with optional reverse ordering.
def sort_text(data, reverse=False):
"""
Sort a list of strings (or a single string split into words) alphabetically.
"""
if isinstance(data, str):
words = data.split()
else:
words = [str(item) for item in data]
return sorted(words, reverse=reverse)
if __name__ == "__main__":
…
How to Summarize Text Statistics in Python
This function returns basic statistics about a string, including character, word, and sentence counts, plus case and digit counts.
def summarize_text(text):
"""Return basic statistics about a string."""
words = text.split()
return {
"characters": len(text),
"words": len(words),
"sentences": text.count(".") + text.count("!") + text.count("?"),
"uppercase": sum(c.isupper() for c in text),
"lowerca…
How to Validate Text Input in Python: A Simple Text Processor
A Python function that validates a text string by trimming whitespace, then returns a dictionary with character, word, and sentence counts.
def validate_text(text: str) -> dict:
"""Analyze a text string and return basic validation statistics."""
stripped = text.strip()
if not stripped:
return {
"valid": False,
"reason": "Text is empty or only whitespace",
"characters": 0,
"words": 0,
…
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.