Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
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.
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…
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.
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))
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.
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)
…
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.
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)
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.
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…
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.
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}'…
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 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.
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…
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.
def capitalize_words(text):
return text.title()
if __name__ == "__main__":
sample = "hello world from python"
result = capitalize_words(sample)
print(result)
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 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.
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…
How to Compare Strings with casefold in Python
Compares two strings ignoring case differences using the casefold() method for proper Unicode normalization.
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}…
How to Compare Two Strings in Python
Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.
def compare_data(first_value, second_value):
"""Compare two string values and return a report."""
if first_value == second_value:
status = "MATCH"
else:
status = "DIFFER"
return {
"first_value": first_value,
"second_value": second_value,
"status": status,
…
How to Convert Data to Strings in Python
Convert common data types like bytes, numbers, containers, and None to readable strings with a safe helper function.
def to_str(value):
"""Convert common types to a readable string, safe for beginners."""
if isinstance(value, bytes):
return value.decode("utf-8")
if isinstance(value, (dict, list, tuple, set)):
return str(value)
if value is None:
return ""
return str(value)
if __name__ == …
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.
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…
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 Count Vowels in a String in Python
Counts uppercase and lowercase vowels in a given string using a set and a generator expression.
def count_vowels(text):
vowels = set("aeiouAEIOU")
return sum(1 for char in text if char in vowels)
if __name__ == "__main__":
sample = "Hello, World!"
result = count_vowels(sample)
print(f"Vowel count in '{sample}': {result}")
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.
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}")
How to Escape HTML in Python
This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.
import html
def escape_user_input(user_input: str) -> str:
"""Escape HTML-sensitive characters for safe display."""
return html.escape(user_input)
if __name__ == "__main__":
sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
safe_output = escape_user_input(sample_user_input)
print("…
How to Filter Text to Only Letters, Numbers, and Spaces in Python
A beginner-friendly function that filters a string to keep only alphabetic characters, digits, and spaces, removing punctuation and symbols.
def filter_text(text, keep_alpha=True, keep_digits=True, keep_spaces=True):
allowed = set()
if keep_alpha:
allowed.update("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
if keep_digits:
allowed.update("0123456789")
if keep_spaces:
allowed.add(" ")
return "".join(ch f…
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.
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…
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…
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.