Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
Find Most Frequent Character in a String in Python
Count character frequencies in a Python string using a dictionary and return the character that appears most often with a max() key function.
def most_frequent_char(s: str) -> str:
if not s:
return ""
char_count = {}
for ch in s:
char_count[ch] = char_count.get(ch, 0) + 1
max_char = max(char_count, key=char_count.get)
return max_char
if __name__ == "__main__":
text = "programming"
result = most_frequent…
How to Format Strings with Named Placeholders in Python
Format a template string using named placeholders with the str.format() method and a dictionary.
def format_named(template, data):
"""Format a template string using named placeholders."""
return template.format(**data)
if __name__ == "__main__":
template = "Hello {name}, you are {age} years old and live in {city}."
data = {"name": "Alice", "age": 30, "city": "London"}
result = format_named(t…
How to Group Data by Category in Python
Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.
def group_by_category(data):
"""Group list of (category, value) tuples into dictionaries of lists."""
groups = {}
for category, value in data:
groups.setdefault(category, []).append(value)
return groups
if __name__ == "__main__":
items = [
("fruit", "apple"),
("veg", "carro…
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,
…
How to parse key=value pairs in Python
Parse a single line of key=value pairs separated by a delimiter into a Python dictionary.
def parse_key_value_pairs(line: str, delimiter: str = "&") -> dict:
"""Parse a single line of key=value pairs into a dictionary."""
pairs = {}
for token in line.split(delimiter):
if not token.strip():
continue
key, _, value = token.partition("=")
pairs[key.strip()] = val…
Browse by section
Each section groups closely related Python snippets.
Strings & text — Python code examples
What you will find here
This page collects strings & text snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.