Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Build CSV row from Python list with proper quoting
Converts a list of fields into a properly quoted CSV row string using the csv module.
import csv
import io
def build_csv_row(fields):
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(fields)
return output.getvalue().rstrip("\r\n")
if __name__ == "__main__":
fields = ["Alice", "Smith", "123 Main St, Apt 4B", "alice@example.com"]
print(build_csv_row(fields))
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'[!@#$%^&*(),.?":…
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 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 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 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 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 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 Pad a String with Zeros in Python
Pad a string to a fixed width by left-filling it with zeros using the built-in str.zfill method.
def pad_zeros(s, width):
return s.zfill(width)
if __name__ == "__main__":
print(repr(pad_zeros("42", 6)))
print(repr(pad_zeros("-7", 5)))
print(repr(pad_zeros("hello", 10)))
print(repr(pad_zeros("123", 3)))
How to Partition a String on the First Delimiter in Python
Split a string into a tuple of (before, delimiter, after) at the first occurrence of a given delimiter, using a custom function or the built-in str.partition.
def partition_string(s, delimiter):
"""Split string into (before, delimiter, after) on the first occurrence."""
for i, ch in enumerate(s):
if ch == delimiter:
return s[:i], ch, s[i+1:]
return s, "", ""
if __name__ == "__main__":
# Single-character delimiter
s1 = "hello,world,h…
How to Round Numbers with f-strings in Python
Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.
def main():
# Values to format with expression-based rounding
price = 19.995
tax_rate = 0.0825
distance = 1234.56789
# Round inside the f-string expression using round()
print(f"Price rounded to cents: ${round(price, 2)}")
# Combine rounding with arithmetic inside the expression
total…
How to Split a String by Comma in Python
Splits a comma-separated string into a list of trimmed items using Python's built-in split and a list comprehension.
def split_csv(line):
return [item.strip() for item in line.split(",")]
if __name__ == "__main__":
sample = "apple, banana, cherry, date"
result = split_csv(sample)
print(result)
print(f"Number of items: {len(result)}")
How to Strip Whitespace in Python
This code demonstrates how to remove leading and trailing whitespace from a string using the built-in strip() method.
def strip_whitespace(text: str) -> str:
return text.strip()
if __name__ == "__main__":
sample = " Hello, world! "
result = strip_whitespace(sample)
print(f"Original: '{sample}'")
print(f"Stripped: '{result}'")
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 Swap Case of Every Character in Python
Swap uppercase to lowercase and lowercase to uppercase for every character in a string using Python's built-in swapcase() method.
def swap_case(text):
"""
Swap uppercase to lowercase and lowercase to uppercase
for every character in the given string.
"""
return text.swapcase()
if __name__ == "__main__":
sample = "Hello World! Python3.9"
result = swap_case(sample)
print(f"Input: {sample}")
print(f"Output: {r…
How to Transform Text in Python with a Helper Function
Build a simple Python helper to strip extra whitespace and convert text to upper, lower, or title case.
def transform_text(text, upper=False, lower=False, strip_whitespace=False, title_case=False):
"""Apply common string transformations for beginners."""
result = text
if strip_whitespace:
result = " ".join(result.split())
if upper and lower:
raise ValueError("Cannot apply both upper and…
How to Translate Characters in a String with str.maketrans in Python
Build and apply character translation tables with str.maketrans and str.translate to replace, delete, or remap letters in a Python string.
def translate_demo():
# Build a translation table: a→1, e→2, i→3, o→4, u→5
table = str.maketrans("aeiou", "12345")
text = "Hello, Python world! Keep coding, friend."
translated = text.translate(table)
print(f"Original: {text}")
print(f"Translated: {translated}")
# Example wit…
How to build a text helper in Python for beginners
This code provides easy-to-use functions for cleaning text, removing punctuation, counting word frequencies, and summarizing strings — perfect for beginners.
def clean_text(text: str) -> str:
"""Clean and normalize a text string."""
text = text.strip()
text = text.replace(" ", " ")
text = text.capitalize()
text = text.replace(".", ".")
return text
def remove_punctuation(text: str) -> str:
"""Remove common punctuation marks from a string."""
…
Normalize unicode accents to ASCII in Python
This code converts accented Unicode characters to ASCII equivalents using the standard library's unicodedata module.
import unicodedata
def normalize_accents(text: str) -> str:
"""Convert accented unicode characters to ASCII equivalents."""
decomposed = unicodedata.normalize('NFD', text)
ascii_text = ''.join(
char for char in decomposed
if unicodedata.category(char) != 'Mn'
)
return unicodedata.n…
Enumerate a Python List with a Custom Start Index
Iterate over a list with an index that starts at a custom value (like 5) using Python's built-in enumerate() function with the start parameter.
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits, start=5):
print(f"{index}: {fruit}")
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.