Python String Functions Comprehensive Cheat
Sheet
Python Built-in String Methods
Case Conversion
s = "Hello World"
[Link]() # "hello world"
[Link]() # "HELLO WORLD"
[Link]() # "Hello World"
[Link]() # "Hello world"
[Link]() # "hELLO wORLD"
[Link]() # "hello world" (aggressive lowercase)
String Testing/Validation
s = "Hello123"
[Link]() # False (contains numbers)
[Link]() # False (contains letters)
[Link]() # True (alphanumeric)
[Link]() # True (ASCII characters only)
[Link]() # False
[Link]() # False
[Link]() # False
[Link]() # False
[Link]() # False
[Link]() # False
[Link]() # True
[Link]() # False (not valid Python identifier)
Whitespace & Trimming
s = " Hello World "
[Link]() # "Hello World" (both ends)
[Link]() # "Hello World " (left end)
[Link]() # " Hello World" (right end)
[Link]('Hd') # "ello Worl" (specific characters)
# Padding
[Link](20) # " Hello World "
[Link](20) # "Hello World "
[Link](20) # " Hello World"
[Link](20) # "00000000Hello World"
Finding & Searching
s = "Hello World Hello"
[Link]('World') # 6 (first occurrence)
[Link]('Hello') # 12 (last occurrence)
[Link]('World') # 6 (like find, but raises exception if not found)
[Link]('Hello') # 12 (like rfind, but raises exception)
[Link]('Hello') # 2 (count occurrences)
[Link]('Hello') # True
[Link]('World') # False
[Link](('Hi', 'Hello')) # True (tuple of prefixes)
Replacement & Modification
s = "Hello World"
[Link]('World', 'Python') # "Hello Python"
[Link]('l', 'L', 1) # "HeLlo World" (replace first occurrence)
# Translation
trans = [Link]('aeiou', '12345')
[Link](trans) # "H2ll4 W4rld"
# Remove characters
[Link]([Link]('', '', 'aeiou')) # "Hll Wrld"
Splitting & Joining
s = "apple,banana,cherry"
[Link](',') # ['apple', 'banana', 'cherry']
[Link](',', 1) # ['apple', 'banana,cherry'] (max splits)
[Link](',', 1) # ['apple,banana', 'cherry'] (right split)
# Advanced splitting
s = "apple\nbanana\tcherry"
[Link]() # ['apple', 'banana\tcherry']
[Link](',') # ('apple', ',', 'banana,cherry')
[Link](',') # ('apple,banana', ',', 'cherry')
# Joining
','.join(['a', 'b', 'c']) # "a,b,c"
''.join(['H', 'e', 'l', 'l', 'o']) # "Hello"
Encoding & Decoding
s = "Hello"
[Link]('utf-8') # b'Hello'
[Link]('ascii') # b'Hello'
b'Hello'.decode('utf-8') # "Hello"
# Handle errors
[Link]('ascii', errors='ignore') # Ignore non-ASCII
[Link]('ascii', errors='replace') # Replace with ?
String Formatting
Old Style (% formatting)
name = "John"
age = 30
"Hello %s, you are %d years old" % (name, age)
"Hello %(name)s, age: %(age)d" % {'name': name, 'age': age}
# Format specifiers
"%d" % 42 # "42" (integer)
"%f" % 3.14159 # "3.141590" (float)
"%.2f" % 3.14159 # "3.14" (2 decimal places)
"%s" % "hello" # "hello" (string)
"%r" % "hello" # "'hello'" (repr)
New Style (.format())
name = "John"
age = 30
# Positional arguments
"Hello {}, you are {} years old".format(name, age)
"Hello {0}, you are {1} years old".format(name, age)
"Hello {1}, you are {0} years old".format(age, name) # Reorder
# Keyword arguments
"Hello {name}, you are {age} years old".format(name=name, age=age)
# Format specifications
"{:.2f}".format(3.14159) # "3.14"
"{:>10}".format("hello") # " hello" (right align)
"{:<10}".format("hello") # "hello " (left align)
"{:^10}".format("hello") # " hello " (center align)
"{:0>10}".format("hello") # "00000hello" (pad with zeros)
F-strings (Python 3.6+)
name = "John"
age = 30
price = 19.99
f"Hello {name}, you are {age} years old"
f"Price: ${price:.2f}" # "Price: $19.99"
f"Age in hex: {age:x}" # "Age in hex: 1e"
f"Name uppercase: {[Link]()}"
f"Expression: {2 + 3}" # "Expression: 5"
# Alignment and padding
f"{name:>10}" # " John" (right align)
f"{name:<10}" # "John " (left align)
f"{name:^10}" # " John " (center align)
f"{age:04d}" # "0030" (pad with zeros)
# Date formatting
from datetime import datetime
now = [Link]()
f"Date: {now:%Y-%m-%d %H:%M:%S}"
Regular Expressions with Strings
Import and Basic Usage
import re
text = "The phone number is 123-456-7890"
pattern = r"\d{3}-\d{3}-\d{4}"
[Link](pattern, text) # Match object or None
[Link](pattern, text) # Match from start only
[Link](pattern, text) # List of all matches
[Link](pattern, text) # Iterator of match objects
[Link](pattern, "XXX", text) # Replace matches
[Link](pattern, text) # Split by pattern
Pattern Compilation
pattern = [Link](r"\d+")
[Link](text)
[Link](text)
[Link]("X", text)
# Flags
pattern = [Link](r"hello", [Link] | [Link])
Common Patterns
# Email validation
email_pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
# Phone numbers
phone_pattern = r"\(\d{3}\)\s*\d{3}-\d{4}" # (123) 456-7890
# URLs
url_pattern = r"https?://[^\s]+"
# Dates
date_pattern = r"\d{1,2}/\d{1,2}/\d{4}" # MM/DD/YYYY
# Words only
word_pattern = r"\b[a-zA-Z]+\b"
# Numbers
number_pattern = r"-?\d+\.?\d*"
Pandas String Functions (.str accessor)
Basic Operations
import pandas as pd
df = [Link]({'text': ['Hello', 'World', 'Python']})
df['text'].[Link]() # Lowercase
df['text'].[Link]() # Uppercase
df['text'].[Link]() # Title case
df['text'].[Link]() # Capitalize first letter
df['text'].[Link]() # Swap case
df['text'].[Link]() # String length
String Testing
df['text'].[Link]() # All alphabetic
df['text'].[Link]() # All digits
df['text'].[Link]() # Alphanumeric
df['text'].[Link]() # All lowercase
df['text'].[Link]() # All uppercase
df['text'].[Link]() # All whitespace
df['text'].[Link]() # Numeric
df['text'].[Link]() # Decimal
Finding & Searching
df['text'].[Link]('hello', case=False) # Boolean mask
df['text'].[Link]('hello|world', regex=True) # Regex pattern
df['text'].[Link]('He') # Starts with
df['text'].[Link]('lo') # Ends with
df['text'].[Link]('l') # Position of substring
df['text'].[Link]('l') # Count occurrences
df['text'].[Link](r'[A-Z]') # Match regex at start
df['text'].[Link](r'[A-Za-z]+') # Full string match
Replacement & Extraction
df['text'].[Link]('l', 'L') # Replace substring
df['text'].[Link](r'[aeiou]', 'X', regex=True) # Regex replace
df['text'].[Link](r'([A-Z])') # Extract with groups
df['text'].[Link](r'([a-z])') # Extract all matches
df['text'].[Link](r'[aeiou]') # Find all pattern matches
Splitting & Slicing
df['text'].[Link]() # Split on whitespace
df['text'].[Link]('l') # Split on character
df['text'].[Link](expand=True) # Split into columns
df['text'].[Link]('l', n=1) # Right split, max splits
df['text'].[Link]('l') # Partition into 3 parts
df['text'].[Link]('l') # Right partition
# Slicing
df['text'].str[0] # First character
df['text'].str[0:3] # First 3 characters
df['text'].str[-1] # Last character
df['text'].str[::2] # Every 2nd character
Padding & Alignment
df['text'].[Link](10, side='left', fillchar='0') # Left pad
df['text'].[Link](10, side='right', fillchar='-') # Right pad
df['text'].[Link](10, side='both', fillchar='*') # Center pad
df['text'].[Link](10, fillchar='=') # Center align
df['text'].[Link](10, fillchar=' ') # Left justify
df['text'].[Link](10, fillchar=' ') # Right justify
df['text'].[Link](10) # Zero fill
Cleaning & Trimming
df['text'].[Link]() # Strip whitespace both ends
df['text'].[Link]() # Strip left whitespace
df['text'].[Link]() # Strip right whitespace
df['text'].[Link]('He') # Strip specific characters
df['text'].[Link]('NFKD') # Unicode normalization
df['text'].[Link]('utf-8') # Encode to bytes
df['text'].[Link]('utf-8') # Decode from bytes
String Constants & Utilities
String Module Constants
import string
string.ascii_letters # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
[Link] # '0123456789'
[Link] # '0123456789abcdefABCDEF'
[Link] # '01234567'
[Link] # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
[Link] # All printable characters
[Link] # ' \t\n\r\x0b\x0c'
String Template
from string import Template
template = Template('Hello $name, you are $age years old')
result = [Link](name='John', age=30)
# Safe substitute (ignores missing keys)
result = template.safe_substitute(name='John')
Advanced String Operations
Multiple String Operations
# Method chaining
text = " HELLO WORLD "
result = [Link]().lower().replace('world', 'python').title()
# "Hello Python"
# Multiple replacements
def multiple_replace(text, replacements):
for old, new in [Link]():
text = [Link](old, new)
return text
replacements = {'hello': 'hi', 'world': 'python'}
multiple_replace('hello world', replacements)
String Performance Tips
# Use join for concatenating many strings
words = ['apple', 'banana', 'cherry']
result = ''.join(words) # Efficient
# Avoid: result = word1 + word2 + word3 # Inefficient for many strings
# Use f-strings for modern Python
name = "John"
f"Hello {name}" # Fast and readable
# Use in operator for membership testing
'hello' in 'hello world' # Efficient
'hello world'.find('hello') != -1 # Less efficient
Common String Patterns
# Remove non-alphanumeric characters
import re
clean_text = [Link](r'[^a-zA-Z0-9\s]', '', text)
# Title case with exceptions
def smart_title(text):
exceptions = ['and', 'or', 'but', 'the', 'a', 'an', 'in', 'on', 'at', 'to']
words = [Link]()
result = []
for i, word in enumerate(words):
if i == 0 or [Link]() not in exceptions:
[Link]([Link]())
else:
[Link]([Link]())
return ' '.join(result)
# Reverse string
text[::-1] # Simple reverse
''.join(reversed(text)) # Alternative method
# Check if palindrome
def is_palindrome(s):
s = [Link](r'[^a-zA-Z0-9]', '', s).lower()
return s == s[::-1]
Quick Reference - Most Used String Operations
# Essential String Methods (Top 25)
[Link]() [Link]() [Link]()
[Link]() [Link]() [Link]()
[Link]() [Link]() [Link]()
[Link]() [Link]() [Link]()
f"Hello {name}" [Link]() [Link]()
[Link]() [Link]() [Link]()
[Link]() [Link]() [Link]()
[Link]() [Link]() len(s)