Python's string methods let you inspect and transform text without writing loops: a string is immutable, and each method returns a new string (or a number, list, or boolean) while leaving the original untouched. The fastest way to learn them is to open a Python REPL or editor, try each method on a short sample string, and check the result with print() or repr() so you can see hidden spaces. Nothing beyond a working Python 3 installation is required.
What You'll Need
- A Python 3 installation. Run
python3 --versionin a terminal (Windows:py --version) to confirm it is installed; if not, download it from python.org. - A place to type code: the interactive prompt (run
python3with no arguments), IDLE, VS Code, or any editor you already use. - A short test string to experiment with, for example
text = " Hello, Python World! ".
Step-by-Step
- Learn the difference between calling a method and using a function. String methods are attached to the string with a dot:
text.upper(). Some related tools are free functions that take the string as an argument, such aslen(text)andstr.replace. If you getAttributeError: 'str' object has no attribute ..., you have misspelled the method or used one that does not exist for strings. - Start with case methods. Create a variable and try
.upper(),.lower(),.title(),.capitalize()and.swapcase(). Print each result. Note that.capitalize()lowercases the rest of the string, so"hELLO".capitalize()gives"Hello", while.title()capitalises every word but will turn"it's"into"It'S". - Strip and pad whitespace. Use
.strip()to remove leading and trailing spaces,.lstrip()and.rstrip()for one side only, and pass characters to strip something else:"...data...".strip("."). Reverse the job with.ljust(10),.rjust(10)or.center(10), optionally with a fill character as a second argument. This is whererepr()helps, because it shows spaces thatprint()hides. - Check what a string contains. Try
.startswith()and.endswith()(they accept a tuple of options, e.g.name.endswith((".jpg", ".png"))), then.find()and.count(). Remember.find()returns-1when the text is missing, which is falsy in anifcheck but is not the same asFalse. Usein, e.g."cat" in text, when all you need is a yes/no answer. - Replace and split text.
.replace(old, new)swaps every match unless you pass a count as the third argument..split()with no argument splits on any run of whitespace and drops empty pieces;.split(",")splits on commas and keeps empty ones. Join the pieces back with", ".join(parts). - Clean data with a loop and list comprehension. The usual real-world pattern is to strip and case-normalise a field before comparing:
if user_input.strip().lower() == "yes":. Chain methods freely, but read the chain left to right, sincetext.strip().upper()starts by stripping. - Validate characters. Use
.isdigit(),.isalpha(),.isalnum(),.isspace()and.isupper()to test the whole string. Be careful that.isdigit()accepts some non-ASCII digit characters, so for strict numberstry/except int(value)is safer. - Use
.format()sparingly. Modern code prefers f-strings such asf"Hello, {name}", but you will still meet"{}".format(value)and%sformatting in older code. Do not mix them in one string. - Write a small script that applies several methods. For example, take a messy line, strip it, lower it, split it into words, count them, and print a formatted result. Save it as a
.pyfile and run it withpython3 filename.pyso your experiments persist. - Check results in the official documentation. The Python docs page on string methods lists every method with examples; search for the method name plus "python str" when you are unsure of an edge case.
Common Mistakes
- Expecting the original to change. Strings are immutable.
text.upper()does nothing unless you assign the result:text = text.upper(). - Using
.replace()to drop characters.text.replace(" ")raisesTypeError; pass both arguments, e.g.text.replace(" ", ""). - Assuming
.find()returnsTrue/False. It returns an index or-1, and index0is falsy, soif text.find("H")fails when the match is at the start. Useinor compare with-1. - Splitting on a single space for user text.
"a b".split(" ")gives empty strings; bare.split()does not. - Case-changing before comparing non-English text.
.lower()behaves differently across languages; for Turkish text,"I".lower()does not give the dotless character you may expect..casefold()is the better choice for case-insensitive comparison. - Confusing
.strip(chars)with removing a prefix."https://x".strip("https://")strips any of those characters from both ends, which removes more than you intend. Use.removeprefix()and.removesuffix()for exact prefixes and suffixes.
If That Did Not Work
Most surprises are visible in the error message. AttributeError means a typo or a non-string value (for example, None returned by a function) is being called with a string method; print type(value) to check. TypeError usually means a method is being called with no argument when it needs one, or a value of the wrong type was passed. If output looks correct but comparisons fail, print both sides with repr() to reveal stray spaces, newlines or invisible characters. If a script works in the prompt but not in a file, check you are running the file you edited and that you saved it.
Tips
- Use
repr()rather thanprint()while experimenting; it shows quotes and escape characters. - Normalise input early: strip, then casefold, then compare. It removes a whole class of bugs.
- Chain methods only where the order is obvious; if a chain gets long, split it across lines or into named steps for readability.
- Prefer
infor existence checks and.find()only when you need the position. - Remember that
.join()is a method of the separator, not of the list:",".join(items), and every item must be a string.
Troubleshooting
- Nothing seemed to happen: you called the method without assigning or printing the result.
- Unexpected number from
.count(): matching is case-sensitive, so"Hello".count("l")counts only lower-case letters within that exact case. Lower or casefold first if you want a case-insensitive count. .join()raisesTypeError: at least one element is a number. Convert withstr()or a comprehension first.- Splitting gives one long item: your separator does not appear in the text; check the actual delimiter with
repr(text). - Multi-line text behaves oddly: use
.splitlines()instead of.split("\n")so Windows and Unix line endings are both handled. - Still stuck: reduce the problem to one line in the interactive prompt and test the method on a literal string before reintroducing variables.
Frequently Asked Questions
Do string methods change the original string?
No. Strings are immutable, so every method returns a new value. Assign the result if you want to keep it.
What is the difference between find() and index()?
.find() returns -1 when the substring is absent; .index() raises ValueError. Use .find() when a missing match is normal.
How do I split a string and remove the empty pieces?
Call .split() with no argument for whitespace, or split on your delimiter and filter: [p for p in parts if p].
Are string methods case-sensitive?
Yes. .startswith(), .find(), .count() and .replace() all match exact case unless you normalise the string first.
What is the difference between strip() and replace()?
.strip() removes characters from the ends only; .replace() replaces occurrences anywhere in the string.
Can I call a string method on a number?
No. Convert first with str(value); otherwise you get an AttributeError.