A quick reference for Python's most useful string methods.

Case Conversion

s = "Hello World"
 
s.lower()       # "hello world"
s.upper()       # "HELLO WORLD"
s.capitalize()  # "Hello world"
s.title()       # "Hello World"
s.swapcase()    # "hELLO wORLD"
s.casefold()    # "hello world" (aggressive lowercase)

Whitespace

s = "  hello world  "
 
s.strip()       # "hello world"
s.lstrip()      # "hello world  "
s.rstrip()      # "  hello world"
 
# Strip specific characters
"...hello...".strip(".")  # "hello"

Splitting and Joining

# Split
"a,b,c".split(",")           # ['a', 'b', 'c']
"a  b  c".split()            # ['a', 'b', 'c']  (any whitespace)
"a,b,c".split(",", 1)        # ['a', 'b,c']     (max splits)
"line1\nline2".splitlines()  # ['line1', 'line2']
 
# Join
",".join(["a", "b", "c"])    # "a,b,c"
" ".join(["hello", "world"]) # "hello world"
"\n".join(lines)             # Join with newlines

Finding and Replacing

s = "hello world"
 
# Find (returns index, -1 if not found)
s.find("world")      # 6
s.find("xyz")        # -1
s.rfind("o")         # 7 (from right)
s.index("world")     # 6 (raises ValueError if not found)
 
# Replace
s.replace("world", "python")  # "hello python"
s.replace("l", "L", 1)        # "heLlo world" (max replacements)
 
# Count
s.count("o")         # 2
s.count("l")         # 3

Checking Content

s = "Hello World"
 
# Start/end
s.startswith("Hello")     # True
s.endswith("World")       # True
s.startswith(("Hi", "Hello"))  # True (tuple of options)
 
# Character types
"hello".isalpha()         # True
"123".isdigit()           # True
"hello123".isalnum()      # True
"   ".isspace()           # True
"hello".islower()         # True
"HELLO".isupper()         # True
"Hello World".istitle()   # True
 
# Membership
"world" in "hello world"  # True

Padding and Alignment

s = "hello"
 
# Padding
s.ljust(10)          # "hello     "
s.rjust(10)          # "     hello"
s.center(11)         # "   hello   "
s.zfill(10)          # "00000hello"
 
# With fill character
s.ljust(10, "-")     # "hello-----"
s.center(11, "*")    # "***hello***"

Formatting

# f-strings (recommended)
name = "Alice"
age = 30
f"Name: {name}, Age: {age}"  # "Name: Alice, Age: 30"
 
# Format method
"Name: {}, Age: {}".format(name, age)
"Name: {0}, Age: {1}".format(name, age)
"Name: {name}".format(name="Alice")
 
# Format specifiers
f"{3.14159:.2f}"     # "3.14"
f"{42:05d}"          # "00042"
f"{1000:,}"          # "1,000"
f"{'hi':>10}"        # "        hi"
f"{'hi':<10}"        # "hi        "
f"{'hi':^10}"        # "    hi    "

Partitioning

s = "hello=world"
 
# Partition (splits at first occurrence)
s.partition("=")     # ('hello', '=', 'world')
s.rpartition("=")    # ('hello', '=', 'world')
 
# Not found
"hello".partition("=")  # ('hello', '', '')

Character Translation

# Translation table
table = str.maketrans("aeiou", "12345")
"hello".translate(table)  # "h2ll4"
 
# Remove characters
table = str.maketrans("", "", "aeiou")
"hello".translate(table)  # "hll"

Common Patterns

Clean user input

user_input = "  Hello World  \n"
cleaned = user_input.strip().lower()  # "hello world"

Parse key-value

line = "name=Alice"
key, _, value = line.partition("=")
# key="name", value="Alice"

Slug generation

title = "Hello World! How Are You?"
slug = title.lower().replace(" ", "-")
# Remove non-alphanumeric (except dash)
slug = "".join(c for c in slug if c.isalnum() or c == "-")
# "hello-world-how-are-you"

CSV parsing (simple)

line = "Alice,25,Engineer"
name, age, role = line.split(",")

Multi-line strings

text = """
First line
Second line
""".strip()
 
lines = text.splitlines()
# ['First line', 'Second line']

Check file extension

filename = "document.pdf"
if filename.lower().endswith((".pdf", ".doc", ".docx")):
    print("Document file")

Quick Reference

MethodDescription
s.lower()Lowercase
s.upper()Uppercase
s.strip()Remove whitespace
s.split(sep)Split into list
sep.join(list)Join list into string
s.replace(old, new)Replace substring
s.find(sub)Find index (-1 if not found)
s.startswith(prefix)Check prefix
s.endswith(suffix)Check suffix
s.isdigit()Check if all digits
s.isalpha()Check if all letters
f"{var}"Format string

String methods return new strings—strings are immutable in Python.

React to this post: