Python String Methods: Cheat Sheet, Real Examples and the strip() Trap
Python string methods are built-in functions such as split(), join(), strip(), replace() and find() that clean, search and reshape text. Strings never change in place, so each method returns a new string. Here are the ones you will actually use, with output we ran and the traps that catch experienced developers.
- Python string methods return new strings; the original never changes, so always assign the result.
strip("w.com")removes characters, not a word: it turnedwww.example.comintoexamplein our run. Useremoveprefix()andremovesuffix()for words."".join(parts)was 15 times faster than+=in a loop in our test.- Use
casefold(), notlower(), for case-insensitive comparison of international text.
Text arrives messy: extra spaces from forms, inconsistent capitals from spreadsheets, commas in the wrong places from exports. Python ships with 47 public string methods to deal with it, which we counted with dir(str). You do not need all of them. This guide covers the ones that solve real problems, shows the exact output from Python 3.13.6, and points out where each one surprises people.
First: strings never change in place
x = "abc"
y = x.upper()
print(x, y) # abc ABC
Strings are immutable. x.upper() did not change x; it returned a new string. Writing name.strip() on its own line does nothing useful. Always write name = name.strip(). This one fact explains most “my method did not work” questions from beginners. If Python basics are still new, our Python tutorial for beginners covers strings from the start.
strip(), lstrip(), rstrip() and the classic trap
s = " Hello, World "
print(repr(s.strip()), repr(s.lstrip()), repr(s.rstrip()))
'Hello, World' 'Hello, World ' ' Hello, World'
With no argument, the strip family removes whitespace, including spaces, tabs and newlines, from both ends, the left only or the right only. Nothing in the middle is touched.
Now the trap. The argument to strip() is a set of characters, not a word:
print("www.example.com".strip("w.com")) # example
print("www.example.com".removeprefix("www.")) # example.com
print("file.tar.gz".removesuffix(".gz")) # file.tar
strip("w.com") removed every w, dot, c, o and m from both ends until it hit another letter, leaving just “example”. To remove a specific prefix or suffix, use removeprefix() and removesuffix(), available since Python 3.9.
Tip: any time you pass a multi-character string to strip(), ask yourself whether you mean “these characters” or “this exact text”. It is almost always the second, so use removeprefix or removesuffix.
split(), rsplit() and splitlines()
print("a,b,,c".split(",")) # ['a', 'b', '', 'c']
print("a b\tc\n".split()) # ['a', 'b', 'c']
print("a,b,c".split(",", 1)) # ['a', 'b,c']
print("a,b,c".rsplit(",", 1)) # ['a,b', 'c']
Two behaviours matter. With an explicit separator, empty fields are kept, so ,, produced an empty string. With no argument, split() splits on any run of whitespace and drops empty pieces, which is usually what you want for words. The optional maxsplit limits the number of splits, and rsplit counts from the right, which is perfect for separating a file extension or the last part of a path.
For text with line breaks, prefer splitlines(): "line1\nline2\r\nline3".splitlines() gave ['line1', 'line2', 'line3'], handling both Unix and Windows endings. Splitting on "\n" would have left a stray \r. For structured data such as CSV, do not split by hand at all; quoted fields contain commas. Use the csv module, as shown in our Python file handling guide.
join(): the opposite of split
print(", ".join(["red", "green", "blue"])) # red, green, blue
", ".join([1, 2])
TypeError: sequence item 0: expected str instance, int found
join() is called on the separator and takes an iterable of strings. It refuses numbers, so convert first: ", ".join(map(str, [1, 2])) gave 1, 2. The separator-first syntax looks odd at first, but it means any iterable works, including generators.
Changing case: lower, upper, title, casefold
t = "hello world"
print(t.upper(), "|", t.title(), "|", t.capitalize(), "|", "HeLLo".swapcase())
print("Straße".lower(), "Straße".casefold())
HELLO WORLD | Hello World | Hello world | hEllO
straße strasse
title() capitalises every word and capitalize() only the first letter of the string. For comparisons, casefold() is the right tool: it applies more aggressive Unicode rules, so the German “ß” became “ss” and now matches “STRASSE”.casefold(). Use a.casefold() == b.casefold() for case-insensitive equality, especially with names and addresses. Encoding issues with international text are covered in our UTF-8 encoding guide.
replace()
print("hello world".replace("o", "0")) # hell0 w0rld
print("hello world".replace("o", "0", 1)) # hell0 world
replace() swaps every occurrence of exact text, or only the first n when you pass a count. It is literal and case-sensitive. For patterns, such as “any run of digits” or “case-insensitive”, switch to the re module; see our Python regex guide.
find(), index(), rfind() and count()
t = "hello world"
print(t.find("o"), t.find("z"), t.index("o"), t.rfind("o"), t.count("o"))
t.index("z")
4 -1 4 7 2
ValueError: substring not found
find() returns the position or -1; index() raises an error instead. That difference matters: -1 is a valid index in Python meaning “last character”, so code like t[t.find("z")] silently returns the wrong character. When you only need to know whether text exists, use "o" in t, which is clearer than either.
startswith() and endswith() with tuples
print("report.pdf".endswith((".pdf", ".doc"))) # True
print("hello world".startswith("hell")) # True
Both accept a tuple of options, which replaces chains of or conditions. They are also safer than slicing, because they never raise errors on short strings.
The is-methods: isdigit, isdecimal, isnumeric and friends
| Expression | Result | Why |
|---|---|---|
"42".isdigit() |
True | All digits |
"-42".isdigit() |
False | The minus sign is not a digit |
"4.2".isdigit() |
False | The dot is not a digit |
"²".isdigit() |
True | Superscript two counts as a digit |
"²".isdecimal() |
False | But it is not a decimal digit |
"Ⅷ".isnumeric() |
True | Roman numeral eight is numeric |
"abc1".isalnum() |
True | Letters and digits only |
" ".isspace() |
True | Only whitespace |
The lesson: isdigit() is not a safe way to validate numbers. It rejects negatives and decimals and accepts superscripts that int() cannot convert. To check user input, try the conversion instead: try: int(s) except ValueError: .... Our exception handling guide shows the pattern.
Padding and alignment
print("7".zfill(3), "ab".center(6, "*"), "ab".ljust(5, ".") + "|", "ab".rjust(5) + "|")
007 **ab** ab...| ab|
zfill pads numbers with zeros, which is handy for invoice numbers and file names that must sort correctly. For anything more complex, f-strings are clearer: f"{name:<10}{price:>8.2f}". See our Python f-strings guide.
partition(): split once, safely
print("key=value=x".partition("=")) # ('key', '=', 'value=x')
print("a b".partition(",")) # ('a b', '', '')
partition always returns exactly three parts: before, separator, after. Even when the separator is missing it does not fail, which makes it ideal for parsing key=value settings: key, _, value = line.partition("=").
translate() for many single-character swaps
table = str.maketrans({"a": "4", "e": "3"})
print("leet speak".translate(table)) # l33t sp34k
When you need to swap or delete many individual characters, one translate() call beats a chain of replace() calls in both speed and readability. Passing str.maketrans("", "", "!?.,") removes punctuation.
Building strings fast: join beats +=
We joined 10,000 short strings 200 times with each approach:
| Method | Time |
|---|---|
s += part in a loop |
0.210 s |
"".join(parts) |
0.014 s |
join was about 15 times faster because it calculates the final size once instead of building many intermediate strings. Collect pieces in a list, then join once. For building lists of pieces, our list comprehension guide helps.
A real cleaning recipe
raw = " asha K , RAVI,li "
names = [p.strip().title() for p in raw.split(",") if p.strip()]
print(", ".join(names)) # Asha K, Ravi, Li
Split on the separator, strip each piece, normalise the case, drop empties, and join back. This four-step pattern handles most messy form and spreadsheet input. Be careful with title() on real names, though: in our run it turned “McDonald” into “Mcdonald”, so only apply it when you are sure the data suits it.
Python string methods cheat sheet
| Task | Method |
|---|---|
| Trim spaces | s.strip() |
| Remove a prefix or suffix | s.removeprefix("x"), s.removesuffix("x") |
| Split into words | s.split() |
| Split lines | s.splitlines() |
| Join a list | ", ".join(items) |
| Compare ignoring case | a.casefold() == b.casefold() |
| Replace text | s.replace(old, new) |
| Check text exists | "x" in s |
| Position or -1 | s.find("x") |
| Starts with any of | s.startswith(("a", "b")) |
| Split once | s.partition("=") |
| Zero-pad | s.zfill(5) |
Final thoughts
A handful of Python string methods handle almost all everyday text work: strip and split to clean, join to rebuild, casefold to compare, replace and translate to edit, and find or in to search. Remember that strings are immutable, that strip takes characters rather than words, and that join beats repeated concatenation. Master those and messy input stops being scary.
Frequently asked questions
Why does my string method not change the string?
Python strings are immutable, so every method returns a new string. Assign the result back, for example name = name.strip().
What is the difference between strip and removeprefix?
strip removes any of the given characters from both ends, one at a time. removeprefix removes one exact piece of text from the start, only if it is there.
What is the difference between split() and splitting on a single space?
split() with no argument splits on any whitespace and drops empty strings. split(” “) splits on single spaces only and keeps empty strings for repeated spaces.
Should I use lower or casefold for comparisons?
Use casefold for case-insensitive comparisons. It handles more Unicode cases, such as the German sharp s, which lower leaves unchanged.
What is the fastest way to concatenate many strings in Python?
Collect the pieces in a list and call “”.join(pieces) once. In our test it was about 15 times faster than adding strings with += in a loop.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.