Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
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 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 Validate Text Strings in Python
Validate strings with a reusable helper that checks type, length limits, and empty string handling.
def is_valid_text(value, min_length=1, max_length=None, allow_empty=False):
"""
Validate if a value is a string and meets length requirements.
Args:
value: The value to validate
min_length: Minimum allowed length (default 1)
max_length: Maximum allowed length (None = no limit)
…
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.