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))
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.
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'[!@#$%^&*(),.?":…
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)
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.
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…
Extract URLs from text with regex in Python
Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.
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)
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 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.
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…
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.
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…
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 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.
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…
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 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.
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",
…
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 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.
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.…
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.
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"…
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.
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}")
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,
…
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.