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

20 February 2026 6 min read

Last updated: 24 September 2026

Share:

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

python
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_"))
text
'Order-1042' 'Order-1042  \n' '  Order-1042'
report_final
report_final
tmp_data

With 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).

python
print("summary.csv".strip(".csv"), "|", "summary.csv".removesuffix(".csv"))
text
ummary | summary

Splitting and joining

python
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"]))
text
['Asha', '  Hyderabad', '', '500081']
['two', 'spaces', 'apart']
['', '', 'two', '', '', 'spaces', '', 'apart', '']
['2026-09-25', '10:15:00']
['a/b/c', 'report.csv']
north | south | east

split() 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:

python
print("key=value=with=equals".partition("="))
print("no separator here".partition("="))
text
('key', '=', 'value=with=equals')
('no separator here', '', '')

Searching

python
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)
text
27 -1
True True
2 invoice INV/1042 for order ORD-77
ValueError: substring not found

find 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

python
a, b = "Straße", "STRASSE"
print(a.lower() == b.lower(), a.casefold() == b.casefold())
print("  hyderabad ".strip().title())
text
False True
Hyderabad

For 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

python
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)
text
'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.
  • translate with str.maketrans replaces or deletes several characters in one pass, for example removing all punctuation from a string.
  • center, ljust and rjust pad 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?

Strings are immutable. Methods return a new string and leave the original untouched, so assign the result: name = name.strip().

What is the fastest way to build a long string in a loop?

Collect the pieces in a list and call "".join(pieces) once at the end, rather than adding to a string with += inside the loop.

How do I check whether a string is empty or only whitespace?

An empty string is falsy, so use if not s for empty, and if not s.strip() for empty or whitespace-only. isspace() returns False for an empty string, which surprises people.

Are string methods faster than regular expressions?

For fixed text, yes: in, startswith, replace and split are simpler and usually faster than an equivalent pattern. Reach for re when the thing you are matching varies.

How do I remove all whitespace, including inside the string?

Use "".join(s.split()), which splits on any whitespace and rejoins with nothing. To collapse runs of spaces to one, use " ".join(s.split()).

String operations, methods and formatting are covered in the strings and regular expressions module of the Python Programming course.

Sources

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.

Explore course