Reference library

Strings & text

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

30 matches
Strings & text easy

Automatically Detect Weak Passwords from Large Password Lists in Python

This Python script identifies weak passwords from a list by checking length, common patterns, sequential characters, and uniform characters, returning those that fail the security checks.

password security validation
Python
import re

COMMON_PASSWORDS_FILE = "common_passwords.txt"

def is_weak(password):
    # Check length
    if len(password) < 8:
        return True
    # Check for common patterns
    if password.lower() in {"password", "123456", "qwerty", "letmein", "admin", "welcome"}:
        return True
    # Check for sequential c…
54 0 Open
Strings & text easy

Build a Secure Password Strength Checker in Python

A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.

password security regex
Python
import re

def password_strength(password: str) -> str:
    score = 0
    if len(password) >= 8:
        score += 1
    if re.search(r'[a-z]', password):
        score += 1
    if re.search(r'[A-Z]', password):
        score += 1
    if re.search(r'\d', password):
        score += 1
    if re.search(r'[!@#$%^&*(),.?":…
55 0 Open
Strings & text easy

Count Characters, Words, and Lines in Python Text

Counts characters, words, lines, and the most common words in a given string using Python's standard library.

text-analysis counter strings
Python
from collections import Counter


def count_data(text):
    """Count characters, words, lines, and most common words in text."""
    char_count = len(text)
    word_count = len(text.split())
    line_count = text.count("\n") + 1
    word_freq = Counter(text.lower().split())
    most_common = word_freq.most_common(3)

…
16 0 Open
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

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

Find the Longest Word in a Sentence in Python

Splits a sentence into words and returns the longest one using the built-in max() function with len as the key.

strings max split
Python
def find_longest_word(sentence: str) -> str:
    words = sentence.split()
    if not words:
        return ""
    return max(words, key=len)

if __name__ == "__main__":
    test_sentence = "The quick brown fox jumps over the lazy dog"
    longest = find_longest_word(test_sentence)
    print(f"Longest word: '{longest}'…
15 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 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 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.

string filter list
Python
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…
12 0 Open
Strings & text easy

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.

string-manipulation text-formatting beginner
Python
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:"…
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 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.

strings text-analysis statistics
Python
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()),
 …
14 0 Open
Strings & text easy

How to Join List of Words into a Sentence in Python

Concatenate a list of strings into a single sentence with spaces using the Python string join() method.

string join list
Python
words = ["Hello", "world", "this", "is", "Python"]
sentence = " ".join(words)
print(sentence)
15 0 Open
Strings & text easy

How to Parse and Clean Text in Python

This code defines three helper functions to parse text into lowercase words, count unique word frequencies, and clean text by removing punctuation and extra whitespace.

text parsing string cleaning word frequency
Python
def extract_words(text: str) -> list[str]:
    """Return a list of lowercase words from the given text."""
    return [word.lower() for word in text.split() if word.isalpha()]


def count_unique_words(text: str) -> dict[str, int]:
    """Return a dictionary with unique words and their frequencies."""
    words = extra…
11 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 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 Validate Text Input in Python: A Simple Text Processor

A Python function that validates a text string by trimming whitespace, then returns a dictionary with character, word, and sentence counts.

text-validation strings input-checking
Python
def validate_text(text: str) -> dict:
    """Analyze a text string and return basic validation statistics."""
    stripped = text.strip()
    if not stripped:
        return {
            "valid": False,
            "reason": "Text is empty or only whitespace",
            "characters": 0,
            "words": 0,
    …
11 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.