Python String Methods Every Developer Should Know
The string methods behind most real text work in Python, grouped by job (cleaning, splitting and joining, searching, comparing, checking) with the traps: strip removing characters rather than a suffix, split() versus split(' '), casefold, and why isdigit accepts characters int() rejects.
GloryTecks Team
Training & Placement Faculty
Last updated: 24 September 2026
Python strings come with over forty methods. You need perhaps fifteen of them for nearly all real work, and a few of those behave differently from what their names suggest. This guide groups the useful ones by job and shows each trap with a line you can run.
Cleaning: strip, and the prefix trap
raw = " Order-1042 \n"
print(repr(raw.strip()), repr(raw.lstrip()), repr(raw.rstrip()))
filename = "report_final.csv"
print(filename.strip(".csv")) # characters, not a suffix
print(filename.removesuffix(".csv")) # exactly the suffix, once
print("tmp_tmp_data".removeprefix("tmp_"))'Order-1042' 'Order-1042 \n' ' Order-1042'
report_final
report_final
tmp_dataWith no argument, strip removes whitespace, including the newline you get from reading a file. With an argument, it removes any combination of those characters from both ends, not that exact string (Python docs: string methods). "report_final.csv".strip(".csv") happens to give the right answer here only because l is not in .csv; try it on "summary.csv" and it removes the s at the start too. For an exact prefix or suffix, use removeprefix and removesuffix, added in Python 3.9 for this reason (PEP 616).
print("summary.csv".strip(".csv"), "|", "summary.csv".removesuffix(".csv"))ummary | summarySplitting and joining
line = "Asha, Hyderabad,,500081"
print(line.split(","))
print(" two spaces apart ".split()) # no argument: any whitespace, no empty strings
print(" two spaces apart ".split(" ")) # one space: empty strings between spaces
print("2026-09-25T10:15:00".split("T", 1))
print("a/b/c/report.csv".rsplit("/", 1))
print(" | ".join(["north", "south", "east"]))['Asha', ' Hyderabad', '', '500081']
['two', 'spaces', 'apart']
['', '', 'two', '', '', 'spaces', '', 'apart', '']
['2026-09-25', '10:15:00']
['a/b/c', 'report.csv']
north | south | eastsplit() with no argument treats any run of whitespace as one separator and drops empty strings, which is what you want for words. split(" ") splits on every single space and keeps the empty strings between them. The optional second argument limits the number of splits, and rsplit counts from the right, so rsplit("/", 1) separates a file name from its folder. join is the reverse of split and the fast way to build a string from many pieces. Note also the empty field and leading spaces in the first line: splitting a CSV line by hand does not handle quoting either, so real CSV belongs to the csv module (reading and writing CSV files).
For a string with exactly one separator, partition is often clearer, because it always returns three parts:
print("key=value=with=equals".partition("="))
print("no separator here".partition("="))('key', '=', 'value=with=equals')
('no separator here', '', '')Searching
text = "invoice INV-1042 for order ORD-77"
print(text.find("ORD"), text.find("XYZ"))
print(text.startswith(("INV", "invoice")), text.endswith("77"))
print(text.count("-"), text.replace("-", "/", 1))
try:
text.index("XYZ")
except ValueError as exc:
print("ValueError:", exc)27 -1
True True
2 invoice INV/1042 for order ORD-77
ValueError: substring not foundfind returns -1 when nothing matches, while index raises ValueError; choose based on whether a missing substring is normal or an error. Beware find in an if: position 0 is falsy, so if text.find("invoice"): is false exactly when the text starts with the word. Use in for "does it contain" questions. startswith and endswith accept a tuple of options, and replace takes an optional count.
Comparing text
a, b = "Straße", "STRASSE"
print(a.lower() == b.lower(), a.casefold() == b.casefold())
print(" hyderabad ".strip().title())False True
HyderabadFor case-insensitive comparison, casefold() is stricter than lower(): it also folds characters such as the German ß to "ss", as the documentation describes. For display, title() capitalises each word, though it has no notion of names like "McDonald" or "O'Brien", so do not use it to "fix" people's names.
Checking characters: isdigit and friends
for s in ["2026", "²", "٣", "-5", "4.5"]:
print(repr(s), s.isdigit(), s.isdecimal())
print(int("٣"))
try:
int("²")
except ValueError as exc:
print("ValueError:", exc)'2026' True True
'²' True False
'٣' True True
'-5' False False
'4.5' False False
3
ValueError: invalid literal for int() with base 10: '²'These methods check Unicode character categories, not "is this a number I can convert". isdigit() accepts the superscript ², which int() rejects, while both isdecimal() and int() accept the Arabic-Indic digit ٣ (Python docs: int). None of them accepts a minus sign or a decimal point. To validate numeric input, do not pre-check at all: call int() or float() and catch ValueError.
Methods worth knowing by name
zfill(5)pads with leading zeros:"42".zfill(5)gives"00042".splitlines()splits on every kind of line ending, including Windows\r\n.translatewithstr.maketransreplaces or deletes several characters in one pass, for example removing all punctuation from a string.center,ljustandrjustpad text to a width, though f-string alignment is usually neater; see Python f-strings.encode("utf-8")turns a string into bytes for writing to networks and binary files.
Putting them together: normalising form input
Text typed by people arrives in every possible shape: " hyderabad", "HYDERABAD ", "Hyderabad City". A small normalising function, applied at the point where data enters your program, prevents three spellings of one city from becoming three groups in a report. Strip the ends, collapse inner runs of whitespace with " ".join(value.split()), and keep two versions: a display form in title case for showing back to people, and a comparison key made with casefold() for matching and de-duplication. Remove known prefixes with removeprefix, never with lstrip. Store the cleaned value, not the raw one, and keep the rules in one function so every form, file import and API uses the same definition of "the same city".
Text and bytes
A str holds text as Unicode characters; bytes holds raw bytes. Files opened in binary mode, network sockets and many APIs deal in bytes, and encode("utf-8") and decode("utf-8") convert between the two. Mixing them raises a TypeError, which is Python protecting you from guessing an encoding. Choose UTF-8 unless a system tells you otherwise, and convert at the edges of your program so that everything inside works with str.
When methods are not enough
String methods match fixed text. For patterns, such as "any order ID of the form three letters, a dash and digits" or "every email address in this document", use regular expressions; see regular expressions in Python. And since strings are immutable, every method returns a new string, which is why chains such as s.strip().lower().replace(" ", "_") read naturally.
Why does my string not change when I call a method on it?
What is the fastest way to build a long string in a loop?
How do I check whether a string is empty or only whitespace?
Are string methods faster than regular expressions?
How do I remove all whitespace, including inside the string?
String operations, methods and formatting are covered in the strings and regular expressions module of the Python Programming course.
Sources
- String Methods — Python documentation
- PEP 616 – String methods to remove prefixes and suffixes — Python Enhancement Proposals
- int() built-in — Python documentation
GloryTecks Team
Training & Placement Faculty
The GloryTecks faculty team mentors learners across Data Science, AI and Data Engineering, with a focus on real-time projects and placement readiness in Hyderabad.
Want to master Python?
Join GloryTecks’ expert-led Python Programming training in Hyderabad with real-time projects and 100% placement support.
Web Scraping with Python: BeautifulSoup and Requests
NextLambda Functions, map, filter and reduce in Python
Related articles
Learn Python from Scratch: A Complete 2026 Roadmap
How to learn Python from zero: install a current version (including the new Windows install manager), then work through seven stages, from values and loops to files, virtual environments, classes and tests, each ending with a small program you should be able to write on your own.
Python Interview Questions: Top 50 with Answers
Fifty conceptual Python interview questions with short, precise answers, grouped by topic: basics, types and mutability, data structures, functions and scope, OOP, iterators and decorators, errors and files, and internals, with runnable examples for the ones people most often get wrong.
Python for Data Science: The Essential Libraries
The Python data science stack explained by the job each library does: NumPy for arrays, pandas for tables, Matplotlib and seaborn for charts, SciPy and statsmodels for statistics, scikit-learn for models and Jupyter for exploration, with one runnable example that passes a real dataset through them.