Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
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 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 Slugify a String in Python
Convert any text into a URL-friendly slug using the standard library's unicodedata and re modules.
import re
import unicodedata
def slugify(text):
text = unicodedata.normalize('NFKD', text)
text = text.encode('ascii', 'ignore').decode('ascii')
text = re.sub(r'[^\w\s-]', '', text).strip().lower()
text = re.sub(r'[-\s]+', '-', text)
return text
if __name__ == "__main__":
title = "Hello, Worl…
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 String isalpha() Method: Check if String is Alphabetic
This code defines a function that uses Python's str.isalpha() method to determine if a string contains only alphabetic characters, with a demonstration on several test strings.
def is_alphabetic(s):
return s.isalpha()
if __name__ == "__main__":
test_strings = ["Hello", "Hello123", "World!", "Python", ""]
for s in test_strings:
print(f"{s!r}: {is_alphabetic(s)}")
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.