Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
How to Align Text in Two Columns with ljust in Python
Format pairs of strings into two aligned columns using ljust padding.
items = [
("apple", "red"),
("banana", "yellow"),
("cherry", "dark red"),
("date", "brown")
]
col1_width = max(len(name) for name, _ in items) + 2
for name, color in items:
print(name.ljust(col1_width) + color)
How to Center Text in a Fixed-Width Banner in Python
Centers any text inside a fixed-width banner using fill characters and computed padding.
def center_text_banner(text, width=40, fill_char="="):
"""Center text within a fixed-width banner."""
if len(text) >= width:
return text
total_padding = width - len(text)
left_padding = total_padding // 2
right_padding = total_padding - left_padding
banner_line = fill_char * w…
How to Check and Manipulate Strings in Python
Demonstrates core string inspection and transformation methods like case conversion, trimming, splitting, and membership checks on a sample string.
text = " Hello, Python Learners! "
print(f"Original: '{text}'")
print(f"Lowercase: '{text.lower()}'")
print(f"Uppercase: '{text.upper()}'")
print(f"Title case: '{text.title()}'")
print(f"Stripped: '{text.strip()}'")
print(f"Length: {len(text)}")
print(f"Replace: '{text.replace('Python', 'Programming')}'")
print(f"S…
How to Convert camelCase to snake_case in Python
Convert camelCase strings to snake_case using a simple Python function that inserts underscores before uppercase letters and lowercases everything.
def camel_to_snake(s):
result = ""
for i, char in enumerate(s):
if char.isupper() and i > 0:
result += "_"
result += char.lower()
return result
if __name__ == "__main__":
test_cases = ["camelCase", "helloWorld", "thisIsACoolExample", "already_snake", "UPPER"]
for case i…
How to Convert snake_case to Title Case in Python
Convert snake_case strings to title case by splitting on underscores, capitalizing each word, and joining them with spaces.
def to_title_case(snake_str):
words = snake_str.split("_")
return " ".join(word.capitalize() for word in words)
if __name__ == "__main__":
examples = ["hello_world", "convert_snake_case", "already_title_case", "multiple__under_scores"]
for example in examples:
print(f"{example!r:35} -> {to_tit…
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 Format Text in Python
A beginner-friendly helper that cleans and changes the case of a string, with options for title, upper, lower, and capitalize.
def format_text(text, case="title", strip_whitespace=True, remove_extra_spaces=True):
"""
Formats a string based on common beginner needs.
Args:
text: Input string to format
case: "title", "upper", "lower", or "capitalize"
strip_whitespace: Remove leading/trailing whitespace
…
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 Inspect String Statistics in Python
A beginner-friendly function that returns detailed statistics about a string, including length, word count, character types, and easy text transformations.
def inspect_text(text: str) -> dict:
"""Return useful stats about a string for beginners."""
words = text.split()
return {
"length": len(text),
"word_count": len(words),
"uppercase": sum(1 for ch in text if ch.isupper()),
"lowercase": sum(1 for ch in text if ch.islower()),
…
How to Pad a String with Zeros in Python
Pad a string to a fixed width by left-filling it with zeros using the built-in str.zfill method.
def pad_zeros(s, width):
return s.zfill(width)
if __name__ == "__main__":
print(repr(pad_zeros("42", 6)))
print(repr(pad_zeros("-7", 5)))
print(repr(pad_zeros("hello", 10)))
print(repr(pad_zeros("123", 3)))
How to Round Numbers with f-strings in Python
Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.
def main():
# Values to format with expression-based rounding
price = 19.995
tax_rate = 0.0825
distance = 1234.56789
# Round inside the f-string expression using round()
print(f"Price rounded to cents: ${round(price, 2)}")
# Combine rounding with arithmetic inside the expression
total…
How to Transform Text in Python with a Helper Function
Build a simple Python helper to strip extra whitespace and convert text to upper, lower, or title case.
def transform_text(text, upper=False, lower=False, strip_whitespace=False, title_case=False):
"""Apply common string transformations for beginners."""
result = text
if strip_whitespace:
result = " ".join(result.split())
if upper and lower:
raise ValueError("Cannot apply both upper and…
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)
Validate email format with regex in Python
A Python function using a regex pattern to validate simple email formats, returning True or False for each input.
import re
def is_valid_email(email):
pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
return bool(re.match(pattern, email))
if __name__ == "__main__":
test_emails = [
"user@example.com",
"first.last@sub.domain.org",
"invalid-email",
"user@.com",
"user@…
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.