Python String Methods
Master Python string methods: strip, split, join, replace, find, upper, lower, and more — with runnable examples, gotchas, and when to use each.
Strings in Python come with a rich set of built-in methods that cover almost every manipulation you will ever need — trimming whitespace, searching, splitting, joining, checking content, and formatting. Because strings are immutable, every method returns a new string (or another value) rather than changing the original.
This chapter covers the most important string methods grouped by purpose, with examples and common gotchas. For background on how strings are created and indexed, see the Python Strings chapter. For slicing syntax, see Slicing Strings.
Case Conversion
upper() and lower()
upper() returns a copy of the string with all letters converted to uppercase; lower() does the opposite.
These are locale-unaware for ASCII letters. For proper locale-aware casing (e.g. Turkish dotted-I), use the locale module or third-party libraries.
title() and capitalize()
title() capitalizes the first letter of every word. capitalize() capitalizes only the first character of the whole string and lowercases everything else.
s = "hello world"
print(s.title()) # Hello World
print(s.capitalize()) # Hello worldGotcha: title() treats any non-letter as a word boundary, so "it's" becomes "It'S". Use the string.capwords() function from the standard library when you need smarter word detection.
swapcase()
Inverts the case of every character — uppercase becomes lowercase and vice versa.
print("Hello World".swapcase()) # hELLO wORLDWhitespace and Padding
strip(), lstrip(), and rstrip()
These remove leading and/or trailing characters (whitespace by default).
s = " Hello World "
print(s.strip()) # "Hello World"
print(s.lstrip()) # "Hello World "
print(s.rstrip()) # " Hello World"You can pass a string of characters to remove — not a prefix/suffix, but any combination of those characters:
print("***hello***".strip("*")) # hello
print("xyzhelloyz".strip("xyz")) # hellocenter(), ljust(), and rjust()
Pad a string to a given width. An optional fill character (default: space) fills the extra space.
print("hi".center(10)) # " hi "
print("hi".ljust(10, "-")) # "hi--------"
print("hi".rjust(10, "-")) # "--------hi"These are useful for building fixed-width text tables.
zfill()
Pads a numeric string with leading zeros to reach a given width. It respects a leading + or - sign.
print("42".zfill(5)) # 00042
print("-7".zfill(5)) # -0007Searching and Counting
find() and rfind()
find(sub) returns the lowest index where sub is found, or -1 if not found. rfind(sub) finds the highest (rightmost) index.
s = "Hello World"
print(s.find("World")) # 6
print(s.find("xyz")) # -1
print(s.rfind("l")) # 9Both accept optional start and end arguments to limit the search range.
index() and rindex()
Work exactly like find() and rfind(), but raise ValueError instead of returning -1 when the substring is not found. Use find() when absence is a normal case; use index() when absence means something went wrong.
s = "Hello World"
print(s.index("World")) # 6
# s.index("xyz") # raises ValueErrorcount()
Returns the number of non-overlapping occurrences of a substring.
print("banana".count("a")) # 3
print("banana".count("an")) # 2
print("aaaa".count("aa")) # 2 (non-overlapping)startswith() and endswith()
Return True if the string starts or ends with the given prefix/suffix. Both accept a tuple of strings to check multiple options at once.
filename = "report.pdf"
print(filename.startswith("report")) # True
print(filename.endswith(".pdf")) # True
print(filename.endswith((".pdf", ".docx"))) # TrueThis is often more readable than slicing: filename[-4:] == ".pdf".
Replacing and Splitting
replace(old, new, count=-1)
Returns a copy with every occurrence of old replaced by new. Pass an integer as the third argument to limit the number of replacements.
replace() does an exact literal match; for pattern-based replacement use the re.sub() function from the Python Regex chapter.
split(sep=None, maxsplit=-1)
Splits the string on sep and returns a list. When sep is omitted (or None), it splits on any whitespace and discards empty strings — ideal for tokenizing user input.
split() always returns a list, even when the delimiter is absent (the list contains just the original string).
rsplit(sep=None, maxsplit=-1)
Like split(), but starts from the right. Useful when you want only the last few parts of a string.
path = "/home/user/documents/file.txt"
print(path.rsplit("/", 1)) # ['/home/user/documents', 'file.txt']splitlines()
Splits on line boundaries (\n, \r\n, \r, and others) and optionally keeps the endings.
text = "line one\nline two\r\nline three"
print(text.splitlines()) # ['line one', 'line two', 'line three']join(iterable)
The reverse of split(). Concatenates every item in an iterable, placing the string it is called on between each item. This is the preferred way to build a string from a list because Python constructs it in one step.
print(", ".join(["apples", "bananas", "cherries"]))
# apples, bananas, cherries
print("".join(["P", "y", "t", "h", "o", "n"]))
# PythonFor more detail, see the Concatenate Strings chapter.
Checking Content
These methods return True or False and are useful for input validation.
| Method | Returns True when… |
|---|---|
isalpha() | All characters are letters |
isdigit() | All characters are digits (0–9) |
isnumeric() | All characters are numeric (includes ², ½, etc.) |
isalnum() | All characters are letters or digits |
isspace() | All characters are whitespace |
islower() | All cased characters are lowercase |
isupper() | All cased characters are uppercase |
istitle() | String is title-cased |
print("Python".isalpha()) # True
print("12345".isdigit()) # True
print("abc123".isalnum()) # True
print(" ".isspace()) # True
print("Hello World".istitle()) # TrueNote: An empty string returns False for all of these methods.
Length
len() is a built-in function, not a string method, but it is fundamental to string work.
Strings are zero-indexed, so valid indices are 0 through len(s) - 1.
Concatenation
The + operator joins two strings. The * operator repeats a string a given number of times.
For joining many strings or building strings in a loop, "".join(list) is significantly faster than + in a loop. See Concatenate Strings for a performance comparison.
Formatting
format() and f-strings
str.format() inserts values into {} placeholders. F-strings (Python 3.6+) do the same thing more concisely and are now the preferred style.
name = "Alice"
score = 95
# str.format()
print("Hello, {}! Your score is {}.".format(name, score))
# f-string (preferred)
print(f"Hello, {name}! Your score is {score}.")
# Hello, Alice! Your score is 95.Both support format specifiers. For the full syntax, see Python String Formatting.
encode()
Converts the string to a bytes object using the given encoding (default utf-8).
s = "café"
print(s.encode("utf-8")) # b'caf\xc3\xa9'
print(s.encode("ascii", errors="replace")) # b'caf?'Quick Reference
| Method | What it does |
|---|---|
s.upper() | All uppercase |
s.lower() | All lowercase |
s.title() | Title case (every word) |
s.capitalize() | First character uppercase |
s.swapcase() | Invert case |
s.strip(chars) | Remove leading/trailing characters |
s.lstrip(chars) | Remove leading characters |
s.rstrip(chars) | Remove trailing characters |
s.center(w, fill) | Center in a field of width w |
s.ljust(w, fill) | Left-align in a field of width w |
s.rjust(w, fill) | Right-align in a field of width w |
s.zfill(w) | Pad with leading zeros |
s.find(sub) | Lowest index of sub, or -1 |
s.rfind(sub) | Highest index of sub, or -1 |
s.index(sub) | Like find() but raises ValueError |
s.count(sub) | Count non-overlapping occurrences |
s.startswith(prefix) | True if string starts with prefix |
s.endswith(suffix) | True if string ends with suffix |
s.replace(old, new) | Replace occurrences |
s.split(sep) | Split into list |
s.rsplit(sep) | Split from right |
s.splitlines() | Split on line endings |
sep.join(iterable) | Join iterable with separator |
s.isalpha() | All letters? |
s.isdigit() | All digits? |
s.isalnum() | All letters or digits? |
s.isspace() | All whitespace? |
s.format(...) | Format with placeholders |
s.encode(enc) | Encode to bytes |