1. Home
  2. Blog
  3. Software Development

Software Development

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.

10 min read
Python string methods cheat sheet

Key takeaways

  • Python string methods return new strings; the original never changes, so always assign the result.
  • strip("w.com") removes characters, not a word: it turned www.example.com into example in our run. Use removeprefix() and removesuffix() for words.
  • "".join(parts) was 15 times faster than += in a loop in our test.
  • Use casefold(), not lower(), 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →