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…
Find the Index of a Substring or Return a Default in Python
Finds the index of a substring using str.find() and returns a specified default value instead of -1 when the substring is not found.
def find_substring_or_default(text, substring, default=-1):
index = text.find(substring)
return index if index != -1 else default
if __name__ == "__main__":
text = "The quick brown fox jumps over the lazy dog"
print(find_substring_or_default(text, "brown"))
print(find_substring_or_default(text, "c…
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 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 Format a Float as Currency in Python
This code defines a function that converts a float to a string formatted as US currency with two decimal places and comma separators.
def format_currency(amount):
return f"${amount:,.2f}"
if __name__ == "__main__":
test_amounts = [1234.5, 0, 9999999.999, -42.867]
for amount in test_amounts:
print(f"{amount} -> {format_currency(amount)}")
How to Mask Credit Card Middle Digits in Python
Mask the middle digits of credit card numbers in a string, keeping only the first 8 and last 4 digits, using regular expressions.
import re
def mask_credit_card(text: str) -> str:
pattern = re.compile(r'(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4})')
return pattern.sub(lambda m: m.group(1) + m.group(2) + '****' + m.group(4), text)
if __name__ == "__main__":
sample = "Card: 1234-5678-9012-3456 and 1111 2222 3333 4444"
print(mas…
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 Use Template Strings for Substitution in Python
This code shows how to use Python's Template class for safe string substitution, replacing placeholders like $name with actual values.
from string import Template
def format_user_message(name, role, company):
template = Template("Hello $name! We are glad to have you as our $role at $company.")
return template.substitute(name=name, role=role, company=company)
if __name__ == "__main__":
result = format_user_message("Alice", "Python Develo…
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."""
…
How to wrap long text to a specified width in Python
Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.
import textwrap
text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""
wrapped = textwrap.fill(text, width=40)
print(wrapped)
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…
Python: Replace Spaces with Hyphens for Slug
Transform a string by stripping surrounding whitespace and replacing each space with a hyphen to create a simple slug.
def slugify(text):
return text.strip().replace(" ", "-")
if __name__ == "__main__":
title = "Hello World Python Example"
result = slugify(title)
print(result)
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.