Reference library

Strings & text

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

94 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 CSV row from Python list with proper quoting

Converts a list of fields into a properly quoted CSV row string using the csv module.

csv quotes strings
Python
import csv
import io


def build_csv_row(fields):
    output = io.StringIO()
    writer = csv.writer(output)
    writer.writerow(fields)
    return output.getvalue().rstrip("\r\n")


if __name__ == "__main__":
    fields = ["Alice", "Smith", "123 Main St, Apt 4B", "alice@example.com"]
    print(build_csv_row(fields))
16 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 medium

Convert Natural Language Dates to Datetime in Python

Parse common natural language date phrases like 'tomorrow' or 'in 3 days' into Python datetime objects using regex and timedelta.

datetime natural-language regex
Python
from datetime import datetime, timedelta
import re

def parse_natural_date(text: str) -> datetime:
    """Convert common natural language date expressions to datetime objects."""
    now = datetime.now()
    text = text.lower().strip()
    
    # Handle relative dates
    patterns = {
        r"today": now,
        r"…
61 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)

…
17 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

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)
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 Most Frequent Character in a String in Python

Count character frequencies in a Python string using a dictionary and return the character that appears most often with a max() key function.

string dictionary counting
Python
def most_frequent_char(s: str) -> str:
    if not s:
        return ""
    
    char_count = {}
    for ch in s:
        char_count[ch] = char_count.get(ch, 0) + 1
    
    max_char = max(char_count, key=char_count.get)
    return max_char

if __name__ == "__main__":
    text = "programming"
    result = most_frequent…
13 0 Open
Strings & text easy

Find the Index of a Substring or Return a Default in Python

Finds the index of a substring using str.find() and returns a specified default value instead of -1 when the substring is not found.

substring string-index str-find
Python
def find_substring_or_default(text, substring, default=-1):
    index = text.find(substring)
    return index if index != -1 else default

if __name__ == "__main__":
    text = "The quick brown fox jumps over the lazy dog"
    print(find_substring_or_default(text, "brown"))
    print(find_substring_or_default(text, "c…
13 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 Align Text in Two Columns with ljust in Python

Format pairs of strings into two aligned columns using ljust padding.

string-formatting ljust alignment
Python
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)
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 Center Text in a Fixed-Width Banner in Python

Centers any text inside a fixed-width banner using fill characters and computed padding.

strings formatting text-alignment
Python
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…
14 0 Open
Strings & text easy

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.

palindrome string case-insensitive
Python
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",
      …
14 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 Check if a String Ends with a File Extension in Python

This code checks whether a filename ends with any of a list of file extensions, handling case insensitivity.

file-extension string-methods endswith
Python
def ends_with_extension(filename, extensions):
    """Check if a filename ends with any of the given extensions."""
    lower_name = filename.lower()
    return any(lower_name.endswith(ext.lower()) for ext in extensions)

if __name__ == "__main__":
    # Test cases
    test_files = ["report.pdf", "image.PNG", "script.…
17 0 Open
Strings & text easy

How to Check if a String Starts With a Prefix Case-Insensitively in Python

This code defines a function that checks if a string starts with a given prefix, ignoring case, using the lower() method.

string-methods case-insensitive startswith
Python
def starts_with_case_insensitive(text, prefix):
    """Check if a string starts with a given prefix, ignoring case."""
    return text.lower().startswith(prefix.lower())


if __name__ == "__main__":
    test_strings = [
        ("Hello World", "hello"),
        ("Python Programming", "PYTHON"),
        ("Data Science"…
15 0 Open
Strings & text easy

How to Check if a String is Alphanumeric in Python

Uses the built-in str.isalnum() method to test whether a string contains only letters and numbers.

string alphanumeric validation
Python
def is_alphanumeric(s: str) -> bool:
    return s.isalnum()

if __name__ == "__main__":
    test_cases = ["Hello123", "Hello World", "12345", "", "Hello@World", "Python3"]
    for case in test_cases:
        result = is_alphanumeric(case)
        print(f"{case!r:15} -> {result}")
13 0 Open
Strings & text easy

How to Check if a String is Numeric in Python

This code provides a function to determine if a string represents a valid numeric value using Python's built-in float() conversion.

numeric validation strings
Python
def is_numeric(s):
    """Check if a string represents a valid numeric value."""
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

if __name__ == "__main__":
    test_cases = ["123", "-45.67", "3.14e10", "0x1A", "abc", "12.5.6", "  42  ", ""]
    for case in test_c…
13 0 Open
Strings & text easy

How to Compare Strings with casefold in Python

Compares two strings ignoring case differences using the casefold() method for proper Unicode normalization.

string comparison casefold unicode
Python
def compare_strings(str1: str, str2: str) -> bool:
    return str1.casefold() == str2.casefold()

if __name__ == "__main__":
    tests = [
        ("HELLO", "hello"),
        ("Straße", "STRASSE"),
        ("Python", "Python"),
        ("Mixed Case", "mixed case"),
    ]
    for s1, s2 in tests:
        print(f"{s1!r}…
13 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.