Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable 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)
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 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 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 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 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 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 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 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 Split Lines and Strip Blank Lines in Python
Split a multiline string into non-empty lines and strip surrounding whitespace using a list comprehension.
import sys
def split_and_strip(text):
"""Split text into non-blank lines, stripping whitespace."""
return [line.strip() for line in text.splitlines() if line.strip()]
if __name__ == "__main__":
sample_text = """ First line
Second line
Third line """
result = split_and_strip(…
How to Split Strings in Python (Beginner-Friendly)
Split Python strings by a delimiter into lists, plus a cleanup variant that strips whitespace and filters empty parts.
def split_text(text, delimiter=" "):
"""Split a string by a delimiter and return a list of parts."""
return text.split(delimiter)
def split_text_with_cleanup(text, delimiter=" "):
"""Split a string, stripping whitespace and filtering empty parts."""
parts = text.split(delimiter)
cleaned = [part.s…
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 Parse Bullet Points in Python
Extract bullet point items from raw text by splitting lines and filtering those that start with '- ' or '* '.
def parse_bullet_points(text):
"""Extract bullet point items from raw text."""
lines = text.splitlines()
items = []
for line in lines:
stripped = line.strip()
if stripped.startswith("- ") or stripped.startswith("* "):
item = stripped[2:]
if item:
…
How to Parse Delimited Data into a Python List
Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.
def parse_data(raw_data):
"""Parse a pipe-delimited string into a list of cleaned items."""
items = raw_data.split("|")
parsed = []
for item in items:
cleaned = item.strip()
if cleaned:
parsed.append(cleaned)
return parsed
if __name__ == "__main__":
data = " apple…
How to Partition a List Around a Pivot in Python
This code splits a list into three parts—elements less than, equal to, and greater than a pivot—then concatenates them to produce a partitioned list while preserving the original order within each group.
def partition_list(lst, pivot):
less = []
equal = []
greater = []
for item in lst:
if item < pivot:
less.append(item)
elif item == pivot:
equal.append(item)
else:
greater.append(item)
return less + equal + greater
if __name__ == "__main__…
How to Process Text into Words in Python
Splits a string into words, strips punctuation, and returns a list of uppercase words using a loop.
def convert_text_processor(text):
words = text.split()
processed = []
for word in words:
clean = word.strip('.,!?;:')
if len(clean) > 0:
processed.append(clean.upper())
return processed
if __name__ == "__main__":
sample_text = "Hello, world! This is a Python e…
How to Process Text with Lists and Loops in Python
A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.
text = "Python makes text processing easy and fun"
words = text.lower().split()
print("Words in the sentence:")
for index, word in enumerate(words, start=1):
print(f"{index}. {word}")
filtered_words = [word for word in words if len(word) > 3]
print(f"\nWords longer than 3 characters: {filtered_words}")
letter…
How to Split a List at the First Occurrence of a Value in Python
This function splits a list into two parts at the first occurrence of a given value, returning the left and right portions.
def split_at_first(lst, value):
try:
idx = lst.index(value)
return lst[:idx], lst[idx:]
except ValueError:
return lst, []
if __name__ == "__main__":
sample = [1, 2, 3, 4, 3, 5]
value = 3
left, right = split_at_first(sample, value)
print("Left:", left)
print("Right:"…
How to Split a List into Chunks in Python
Split a list into fixed-size sublists using a simple list comprehension with slicing.
def chunk_list(lst, size):
"""Split a list into sublists of given size."""
return [lst[i:i + size] for i in range(0, len(lst), size)]
if __name__ == "__main__":
sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(chunk_list(sample, 3))
How to split a list by condition in Python
Splits a list into two lists based on a condition function, returning matched and unmatched items.
def split_by_condition(items, condition):
"""
Split a list into two lists based on a condition.
The first list contains items where condition(item) is True,
the second list contains the rest.
"""
matched = []
unmatched = []
for item in items:
if condition(item):
matc…
How to unzip a list of pairs into two lists in Python
Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.
def unzip(pairs):
"""Split a list of (a, b) pairs into two separate lists."""
if not pairs:
return [], []
firsts = []
seconds = []
for a, b in pairs:
firsts.append(a)
seconds.append(b)
return firsts, seconds
if __name__ == "__main__":
pairs = [(1, 'a'), (…
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.