Reference library

Strings & text

Format, split, join, parse, and clean text — everyday Python string patterns.

34 matches
Strings & text easy

Extract Data from Strings in Python: Beginner's Guide

A beginner-friendly helper that splits a comma-separated string into a list, shows word count, and extracts the first and last words using Python's split() and join() methods.

string split join
Python
text = "python,string,extract,beginner"

words = text.split(",")

print("Full text:", text)
print("Word count:", len(words))
print("First word:", words[0])
print("Last word:", words[-1])

joined = " | ".join(words)
print("Joined with separator:", joined)
15 0 Open
Strings & text easy

Extract Email-Like Tokens from Text in Python

Uses a regular expression to find all email-like tokens in a string, returning them as a list with re.findall.

regex email findall
Python
import re

def extract_email_like_tokens(text):
    pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
    return re.findall(pattern, text)

if __name__ == "__main__":
    sample_text = (
        "Contact us at support@example.com or sales@company.co.uk. "
        "Invalid: hello@world, user@.com, test@do…
17 0 Open
Strings & text easy

Extract URLs from text with regex in Python

Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.

regex url text-processing
Python
import re

text = """
Visit https://www.example.com for docs.
Contact support@mysite.org.
Check http://localhost:8000/api or ftp://files.example.net.
"""

url_pattern = r'https?://[^\s]+'

urls = re.findall(url_pattern, text)

for url in urls:
    print(url)
14 0 Open
Strings & text easy

Find Data From a String in Python: Stats, Clean, Keywords

Three helper functions for beginners: compute character/word/sentence stats, normalize whitespace and case, and extract unique sorted keywords from a string.

strings text-processing keywords
Python
def get_text_stats(text):
    """Return basic statistics about a string."""
    words = text.split()
    sentences = text.replace('!', '.').replace('?', '.').split('.')
    sentences = [s for s in sentences if s.strip()]
    return {
        'characters': len(text),
        'words': len(words),
        'sentences': le…
14 0 Open
Strings & text easy

How to Build a Basic Text Processor in Python

Split text into sentences, count words, find the longest word, and convert text to uppercase — all with pure Python string methods.

string text-processing split
Python
text = """The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!"""

sentences = text.split(". ")
word_count = 0
longest_word = ""

for sentence in sentences:
    words = sentence.split()
    word_count += len(words)
    for word in words:
        clea…
14 0 Open
Strings & text easy

How to Build a Text Processor in Python

This code defines functions to count words, sentences, and find the longest word in a text, then prints basic statistics like uppercase and lowercase versions.

text-processing strings word-count
Python
def count_words(text):
    return len(text.split())


def count_sentences(text):
    sentence_endings = ".!?"
    count = 0
    for char in text:
        if char in sentence_endings:
            count += 1
    return count


def longest_word(text):
    words = text.split()
    if not words:
        return ""
    retur…
14 0 Open
Strings & text easy

How to Capitalize First Letter of Each Word in Python

Capitalizes the first letter of every word in a string using the built-in title() method.

capitalization strings title
Python
def capitalize_words(text):
    return text.title()

if __name__ == "__main__":
    sample = "hello world from python"
    result = capitalize_words(sample)
    print(result)
16 0 Open
Strings & text easy

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.

strings text-processing beginners
Python
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…
15 0 Open
Strings & text easy

How to Convert and Process Text in Python

This code cleans, converts, splits, joins, counts, replaces, reverses, and finds substrings in a text string using Python's standard string methods.

strings text processing methods
Python
text = "  hello world, python is fun!  "

# Clean up whitespace
cleaned = text.strip()

# Convert to title case
titled = cleaned.title()

# Split into words
words = cleaned.split()

# Join with hyphens
hyphenated = "-".join(words)

# Count occurrences of a letter
letter_count = cleaned.count("o")

# Replace a word
rep…
11 0 Open
Strings & text easy

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.

snake-case string-formatting text-processing
Python
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…
12 0 Open
Strings & text easy

How to Count Words in a String in Python

Split a paragraph on whitespace and return the number of words using Python's built-in string methods.

strings word-count split
Python
def count_words(paragraph: str) -> int:
    words = paragraph.split()
    return len(words)


if __name__ == "__main__":
    paragraph = "The quick brown fox jumps over the lazy dog."
    result = count_words(paragraph)
    print(f"Word count: {result}")
13 0 Open
Strings & text easy

How to Generate Initials from a Full Name in Python

Extract and uppercase the first letter of each word in a full name to produce initials using standard string methods.

strings initialism text-processing
Python
def generate_initials(full_name):
    parts = full_name.strip().split()
    initials = ''.join(part[0].upper() for part in parts if part)
    return initials

if __name__ == "__main__":
    name = "john f. kennedy"
    print(generate_initials(name))
14 0 Open
Strings & text easy

How to Generate Text Helper Functions in Python

Three simple Python functions that repeat, join, and count characters in strings for beginners.

strings text-processing functions
Python
def repeat_text(text, times):
    """Repeat a string a given number of times."""
    return text * times


def join_words(words, separator=" "):
    """Join a list of words into a single string."""
    return separator.join(words)


def count_characters(text):
    """Count character occurrences in a string."""
    ret…
14 0 Open
Strings & text easy

How to Highlight Search Terms in Python Text

Highlights all case-insensitive occurrences of a search term in a string by wrapping them in markers.

string search highlight
Python
def highlight_search_term(text: str, term: str) -> str:
    """Highlight all occurrences of term in text using terminal-style markers."""
    if not term:
        return text

    term_lower = term.lower()
    result = []
    i = 0

    while i < len(text):
        # Check if the term starts at position i (case-insens…
11 0 Open
Strings & text easy

How to Normalize Text in Python

This code defines a function that trims, lowercases, and collapses extra whitespace in a string, returning normalized text.

string normalization whitespace
Python
def normalize_text(text: str) -> str:
    normalized = " ".join(text.lower().strip().split())
    return normalized


if __name__ == "__main__":
    raw = "   Hello,   WORLD!   This is   a  test.   "
    print(normalize_text(raw))
14 0 Open
Strings & text easy

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.

string partition split
Python
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…
13 0 Open
Strings & text easy

How to Process Lines of Text in Python

Strip whitespace, split a multi-line string, count words per line, and print structured summaries using basic string methods and loops.

strings text-processing splitlines
Python
text = """   Python is great!
Coding is fun.
   Python skills help you grow.   """

lines = text.strip().splitlines()
line_count = len(lines)

processed = []
for line in lines:
    stripped = line.strip()
    word_count = len(stripped.split())
    processed.append({
        "original": line,
        "stripped": stripp…
13 0 Open
Strings & text easy

How to Process Text in Python

This code processes multiline text by splitting lines, stripping whitespace, counting words and characters, and converting to lowercase.

text-processing strings beginner
Python
def process_text(text):
    lines = text.split("\n")
    clean_lines = []
    for line in lines:
        stripped = line.strip()
        if stripped:
            tokens = stripped.split()
            title_case = stripped.lower()
            clean_lines.append({
                "raw": stripped,
                "word_c…
12 0 Open
Strings & text easy

How to Process Text in Python: Normalize Whitespace and Count Words

A beginner-friendly function that normalizes whitespace in a string and counts total and unique words using Python's standard library.

strings text-processing word-count
Python
def process_text(text):
    """Basic text processing: normalize whitespace and count words."""
    normalized = " ".join(text.split())
    word_count = len(normalized.split())
    char_count = len(normalized)
    
    # Count unique words
    unique_words = set(normalized.lower().split())
    unique_count = len(unique…
12 0 Open
Strings & text easy

How to Slugify a String in Python

Convert any text into a URL-friendly slug using the standard library's unicodedata and re modules.

slugify string url
Python
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…
14 0 Open
Strings & text easy

How to Sort Text Alphabetically in Python

Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.

sorting text-processing strings
Python
def sort_words(text):
    """Sort words alphabetically (case-insensitive), preserving case."""
    words = text.split()
    return sorted(words, key=str.lower)


def sort_lines(text):
    """Sort lines alphabetically (case-insensitive), preserving case."""
    lines = [line for line in text.splitlines() if line.strip(…
11 0 Open
Strings & text easy

How to Sort Text in Python with a Simple Helper Function

A compact helper function that sorts a list of strings or splits a string into words and sorts them alphabetically, with optional reverse ordering.

sorting strings text-processing
Python
def sort_text(data, reverse=False):
    """
    Sort a list of strings (or a single string split into words) alphabetically.
    """
    if isinstance(data, str):
        words = data.split()
    else:
        words = [str(item) for item in data]
    return sorted(words, reverse=reverse)


if __name__ == "__main__":
 …
11 0 Open
Strings & text easy

How to Summarize Text Statistics in Python

This function returns basic statistics about a string, including character, word, and sentence counts, plus case and digit counts.

strings text-processing statistics
Python
def summarize_text(text):
    """Return basic statistics about a string."""
    words = text.split()
    return {
        "characters": len(text),
        "words": len(words),
        "sentences": text.count(".") + text.count("!") + text.count("?"),
        "uppercase": sum(c.isupper() for c in text),
        "lowerca…
13 0 Open
Strings & text easy

How to Swap Case of Every Character in Python

Swap uppercase to lowercase and lowercase to uppercase for every character in a string using Python's built-in swapcase() method.

string swapcase case conversion
Python
def swap_case(text):
    """
    Swap uppercase to lowercase and lowercase to uppercase 
    for every character in the given string.
    """
    return text.swapcase()

if __name__ == "__main__":
    sample = "Hello World! Python3.9"
    result = swap_case(sample)
    print(f"Input:  {sample}")
    print(f"Output: {r…
14 0 Open

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.