Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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)
How to Align Text in Two Columns with ljust in Python
Format pairs of strings into two aligned columns using ljust padding.
items = [
("apple", "red"),
("banana", "yellow"),
("cherry", "dark red"),
("date", "brown")
]
col1_width = max(len(name) for name, _ in items) + 2
for name, color in items:
print(name.ljust(col1_width) + color)
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 Center Text in a Fixed-Width Banner in Python
Centers any text inside a fixed-width banner using fill characters and computed padding.
def center_text_banner(text, width=40, fill_char="="):
"""Center text within a fixed-width banner."""
if len(text) >= width:
return text
total_padding = width - len(text)
left_padding = total_padding // 2
right_padding = total_padding - left_padding
banner_line = fill_char * w…
How to Check Palindrome in Python (Ignore Case and Spaces)
Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.
def is_palindrome(text: str) -> bool:
cleaned = ''.join(char.lower() for char in text if char.isalnum())
return cleaned == cleaned[::-1]
if __name__ == "__main__":
test_cases = [
"A man, a plan, a canal: Panama",
"race a car",
"Was it a car or a cat I saw?",
"hello",
…
How to Check and Manipulate Strings in Python
Demonstrates core string inspection and transformation methods like case conversion, trimming, splitting, and membership checks on a sample string.
text = " Hello, Python Learners! "
print(f"Original: '{text}'")
print(f"Lowercase: '{text.lower()}'")
print(f"Uppercase: '{text.upper()}'")
print(f"Title case: '{text.title()}'")
print(f"Stripped: '{text.strip()}'")
print(f"Length: {len(text)}")
print(f"Replace: '{text.replace('Python', 'Programming')}'")
print(f"S…
How to Check if a String Ends with a File Extension in Python
This code checks whether a filename ends with any of a list of file extensions, handling case insensitivity.
def ends_with_extension(filename, extensions):
"""Check if a filename ends with any of the given extensions."""
lower_name = filename.lower()
return any(lower_name.endswith(ext.lower()) for ext in extensions)
if __name__ == "__main__":
# Test cases
test_files = ["report.pdf", "image.PNG", "script.…
How to Check if a String Starts With a Prefix Case-Insensitively in Python
This code defines a function that checks if a string starts with a given prefix, ignoring case, using the lower() method.
def starts_with_case_insensitive(text, prefix):
"""Check if a string starts with a given prefix, ignoring case."""
return text.lower().startswith(prefix.lower())
if __name__ == "__main__":
test_strings = [
("Hello World", "hello"),
("Python Programming", "PYTHON"),
("Data Science"…
How to Check if a String is Alphanumeric in Python
Uses the built-in str.isalnum() method to test whether a string contains only letters and numbers.
def is_alphanumeric(s: str) -> bool:
return s.isalnum()
if __name__ == "__main__":
test_cases = ["Hello123", "Hello World", "12345", "", "Hello@World", "Python3"]
for case in test_cases:
result = is_alphanumeric(case)
print(f"{case!r:15} -> {result}")
How to Check if a String is Numeric in Python
This code provides a function to determine if a string represents a valid numeric value using Python's built-in float() conversion.
def is_numeric(s):
"""Check if a string represents a valid numeric value."""
try:
float(s)
return True
except (ValueError, TypeError):
return False
if __name__ == "__main__":
test_cases = ["123", "-45.67", "3.14e10", "0x1A", "abc", "12.5.6", " 42 ", ""]
for case in test_c…
How to Compare Strings with casefold in Python
Compares two strings ignoring case differences using the casefold() method for proper Unicode normalization.
def compare_strings(str1: str, str2: str) -> bool:
return str1.casefold() == str2.casefold()
if __name__ == "__main__":
tests = [
("HELLO", "hello"),
("Straße", "STRASSE"),
("Python", "Python"),
("Mixed Case", "mixed case"),
]
for s1, s2 in tests:
print(f"{s1!r}…
How to Compare Two Strings in Python
Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.
def compare_data(first_value, second_value):
"""Compare two string values and return a report."""
if first_value == second_value:
status = "MATCH"
else:
status = "DIFFER"
return {
"first_value": first_value,
"second_value": second_value,
"status": status,
…
How to Convert Data to Strings in Python
Convert common data types like bytes, numbers, containers, and None to readable strings with a safe helper function.
def to_str(value):
"""Convert common types to a readable string, safe for beginners."""
if isinstance(value, bytes):
return value.decode("utf-8")
if isinstance(value, (dict, list, tuple, set)):
return str(value)
if value is None:
return ""
return str(value)
if __name__ == …
How to Convert and Process Text in Python
This code cleans, converts, splits, joins, counts, replaces, reverses, and finds substrings in a text string using Python's standard string methods.
text = " hello world, python is fun! "
# Clean up whitespace
cleaned = text.strip()
# Convert to title case
titled = cleaned.title()
# Split into words
words = cleaned.split()
# Join with hyphens
hyphenated = "-".join(words)
# Count occurrences of a letter
letter_count = cleaned.count("o")
# Replace a word
rep…
How to Convert camelCase to snake_case in Python
Convert camelCase strings to snake_case using a simple Python function that inserts underscores before uppercase letters and lowercases everything.
def camel_to_snake(s):
result = ""
for i, char in enumerate(s):
if char.isupper() and i > 0:
result += "_"
result += char.lower()
return result
if __name__ == "__main__":
test_cases = ["camelCase", "helloWorld", "thisIsACoolExample", "already_snake", "UPPER"]
for case i…
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 Vowels in a String in Python
Counts uppercase and lowercase vowels in a given string using a set and a generator expression.
def count_vowels(text):
vowels = set("aeiouAEIOU")
return sum(1 for char in text if char in vowels)
if __name__ == "__main__":
sample = "Hello, World!"
result = count_vowels(sample)
print(f"Vowel count in '{sample}': {result}")
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 Detect Expired Domains Using Python
Parse a list of domain registration data and compare expiry dates to today to find expired domains.
import datetime
# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
('example.com', '2020-01-15', '2024-01-15'), # Expired
('google.com', '1997-09-15', '2026-09-15'), # Still active
('test-site.org', '2019-06-01', '2023-06-0…
How to Detect PII in Documents Using Python
Use regex patterns to automatically detect emails, phone numbers, SSNs, and credit card numbers in text documents.
import re
from typing import List, Dict
def detect_pii(text: str) -> Dict[str, List[str]]:
patterns = {
"email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
"phone": r"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
"ssn": r"\b\d{3}-\d{2}-\d{4}\b",
"credit_card": r"\b\d{4}[- ]?\d{4}[-…
How to Detect if a String Contains Only ASCII in Python
This code defines a function that checks whether every character in a given string is an ASCII character (Unicode code point < 128) and demonstrates it with multiple test cases.
def is_ascii_only(text: str) -> bool:
"""Return True if all characters in text are ASCII, False otherwise."""
return all(ord(char) < 128 for char in text)
if __name__ == "__main__":
# Test cases
samples = [
"Hello, world!",
"Café au lait",
"日本語テキスト",
"ASCII only 123",
…
How to Encode and Decode UTF-8 in Python
Convert a Python string to UTF-8 bytes with .encode() and back to text with .decode(), with a simple demo function.
def encode_decode_demo(text: str):
encoded = text.encode("utf-8")
decoded = encoded.decode("utf-8")
print(f"Original string: {text}")
print(f"Encoded bytes: {encoded}")
print(f"Decoded string: {decoded}")
print(f"Match: {text == decoded}")
if __name__ == "__main__":
encode_decode_demo("Hel…
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.