Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
How to Check Palindrome in Python (Ignore Case and Spaces)
Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.
def is_palindrome(text: str) -> bool:
cleaned = ''.join(char.lower() for char in text if char.isalnum())
return cleaned == cleaned[::-1]
if __name__ == "__main__":
test_cases = [
"A man, a plan, a canal: Panama",
"race a car",
"Was it a car or a cat I saw?",
"hello",
…
How to Filter Text to Only Letters, Numbers, and Spaces in Python
A beginner-friendly function that filters a string to keep only alphabetic characters, digits, and spaces, removing punctuation and symbols.
def filter_text(text, keep_alpha=True, keep_digits=True, keep_spaces=True):
allowed = set()
if keep_alpha:
allowed.update("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
if keep_digits:
allowed.update("0123456789")
if keep_spaces:
allowed.add(" ")
return "".join(ch f…
How to Filter a List of Strings by Keyword in Python
A helper function filters a list of strings by a keyword search with optional case sensitivity.
def filter_strings(items, keyword, case_sensitive=False):
"""
Filter a list of strings by a keyword.
Args:
items: list of strings to filter
keyword: substring to search for
case_sensitive: if True, match case exactly
Returns:
list of strings containing the keyw…
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…
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.