Python String Methods: The Complete Reference
Python strings come with over 40 built-in methods. Here are the ones you’ll actually use.
Case Conversion
text = "hello World"
text.upper() # 'HELLO WORLD'
text.lower() # 'hello world'
text.capitalize() # 'Hello world'
text.title() # 'Hello World'
text.swapcase() # 'HELLO wORLD'Checking Content
text = "Hello123"
text.isalpha() # False (has digits)
text.isdigit() # False (has letters)
text.isalnum() # True (letters + digits)
text.islower() # False
text.isupper() # False
text.isspace() # False
text.startswith("Hel") # True
text.endswith("123") # TrueSearching
text = "hello world hello"
text.find("world") # 6 (index of first match)
text.find("xyz") # -1 (not found)
text.index("world") # 6 (like find, but raises ValueError)
text.rfind("hello") # 12 (search from right)
text.count("hello") # 2
"in" in text # True (in operator)Modifying
text = " hello world "
text.strip() # 'hello world' (remove leading/trailing whitespace)
text.lstrip() # 'hello world ' (left only)
text.rstrip() # ' hello world' (right only)
text.replace("world", "Python") # ' hello Python '
"a,b,c".replace(",", " | ") # 'a | b | c'Splitting and Joining
# Split
"a,b,c".split(",") # ['a', 'b', 'c']
"a b c".split() # ['a', 'b', 'c'] (splits on any whitespace)
"a,b,c".split(",", maxsplit=1) # ['a', 'b,c']
"line1\nline2\nline3".splitlines() # ['line1', 'line2', 'line3']
# Join
", ".join(["a", "b", "c"]) # 'a, b, c'
"".join(["h", "e", "l", "l", "o"]) # 'hello'
" -> ".join(["a", "b", "c"]) # 'a -> b -> c'Padding and Alignment
text = "hello"
text.center(11) # ' hello '
text.ljust(10) # 'hello '
text.rjust(10) # ' hello'
text.zfill(8) # '000hello' (pad with zeros)
"42".zfill(5) # '00042'Stripping Specific Characters
"file.txt.txt".strip(".txt") # 'file' (removes . t x)
"file.txt.txt".removesuffix(".txt") # 'file.txt' (Python 3.9+)
"file.txt.txt".removeprefix("file") # '.txt.txt' (Python 3.9+)
" hello ".strip(" h") # 'ello'Formatting
f-strings (Python 3.6+, recommended)
name = "Alice"
age = 30
f"{name} is {age} years old" # 'Alice is 30 years old'
f"{name:>10}" # ' Alice' (right align)
f"{name:<10}" # 'Alice ' (left align)
f"{name:^10}" # ' Alice ' (center)
f"{age:03d}" # '030' (zero pad)
f"{3.14159:.2f}" # '3.14' (2 decimal places)
f"{1000:,}" # '1,000' (thousands separator)
f"{0.25:.1%}" # '25.0%' (percentage).format() method
"{} is {} years old".format("Alice", 30)
"{name} is {age} years old".format(name="Alice", age=30)
"{1} is {0} years old".format(30, "Alice")Encoding and Characters
"hello".encode("utf-8") # b'hello'
"hello".encode("utf-16") # b'\xff\xfeh\x00e\x00...'
ord("A") # 65 (Unicode code point)
chr(65) # 'A'Common Patterns
# Remove punctuation
import string
"hello, world!".translate(str.maketrans("", "", string.punctuation))
# 'hello world'
# Check if string is a number
"42".isdigit() # True
"42.5".isdigit() # False
"42.5".replace(".", "").isdigit() # True (hacky)
# Better: try parsing
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
# Split lines preserving line endings
"a\nb\nc".splitlines(keepends=True) # ['a\n', 'b\n', 'c']
# Reverse a string
"hello"[::-1] # 'olleh'Related: Learn Python virtual environments and fix pip errors.