Course topics

By WebNest Studio

Python Tutorial

Python String Methods Reference

Strings are the most used data type in almost every program — names, emails, messages, file contents, API responses. Python's str type comes with over 40 built-in methods for changing case, searching, testing content, splitting, joining, trimming, padding and replacing text.

This lesson is a complete, example-driven reference to the string methods, grouped by what they do. Remember that strings are immutable: every method returns a new string and leaves the original unchanged.

Case Conversion

upper(), lower(), capitalize() (first character upper, rest lower), title() (each word capitalised), swapcase() and casefold() (an aggressive lowercase for case-insensitive comparison, handling characters like German "ß").

Searching and Counting

find(sub, start, end) returns the lowest index or -1; rfind() searches from the right. index() and rindex() do the same but raise ValueError when not found. count(sub) counts non-overlapping occurrences; startswith() and endswith() accept a string or a tuple of strings.

Testing Content (is... methods)

isalpha(), isdigit(), isdecimal(), isnumeric(), isalnum(), isspace(), islower(), isupper(), istitle(), isidentifier(), isprintable() and isascii() return True or False. isdecimal() accepts only 0–9 style digits, isdigit() also accepts superscripts, and isnumeric() also accepts characters like "½".

Splitting, Joining and Partitioning

split(sep, maxsplit) and rsplit() break a string into a list (no separator means "any whitespace"); splitlines() splits on line breaks; partition(sep) and rpartition(sep) return a 3-tuple (before, sep, after); sep.join(iterable) glues strings together.

Trimming, Padding and Alignment

strip(), lstrip(), rstrip() remove whitespace (or given characters); removeprefix() and removesuffix() remove an exact prefix/suffix. center(width, fill), ljust(), rjust() pad to a width; zfill(width) pads numbers with zeros; expandtabs(n) replaces tabs with spaces.

Replacing, Translating and Encoding

replace(old, new, count) replaces substrings; maketrans() + translate() replace or delete many single characters at once; encode(encoding) converts text to bytes (and bytes.decode() reverses it); format() and format_map() fill templates.

Examples

Case methods

Python
s = "python PROGRAMMING is fun"
print(s.upper())
print(s.lower())
print(s.capitalize())
print(s.title())
print(s.swapcase())
print("Straße".casefold() == "STRASSE".casefold())
Output
PYTHON PROGRAMMING IS FUN
python programming is fun
Python programming is fun
Python Programming Is Fun
PYTHON programming IS FUN
True

Searching and counting

Python
text = "banana bandana"
print(text.find("an"), text.rfind("an"), text.find("xyz"))
print(text.index("band"))
print(text.count("an"), text.count("a", 0, 6))
print(text.startswith("ban"), text.endswith(("na", "xy")))
try:
    text.index("xyz")
except ValueError as e:
    print("ValueError:", e)
Output
1 11 -1
7
4 3
True True
ValueError: substring not found

Testing content with is... methods

Python
tests = ["Python", "2026", "abc123", "   ", "Hello World", "user_name", "½", "²"]
for t in tests:
    print(f"{t!r:14} alpha={t.isalpha()!s:5} decimal={t.isdecimal()!s:5} "
          f"digit={t.isdigit()!s:5} numeric={t.isnumeric()!s:5} alnum={t.isalnum()!s:5} "
          f"space={t.isspace()!s:5} title={t.istitle()!s:5} ident={t.isidentifier()}")
Output
'Python'       alpha=True  decimal=False digit=False numeric=False alnum=True  space=False title=True  ident=True
'2026'         alpha=False decimal=True  digit=True  numeric=True  alnum=True  space=False title=False ident=False
'abc123'       alpha=False decimal=False digit=False numeric=False alnum=True  space=False title=False ident=True
'   '          alpha=False decimal=False digit=False numeric=False alnum=False space=True  title=False ident=False
'Hello World'  alpha=False decimal=False digit=False numeric=False alnum=False space=False title=True  ident=False
'user_name'    alpha=False decimal=False digit=False numeric=False alnum=False space=False title=False ident=True
'½'            alpha=False decimal=False digit=False numeric=True  alnum=True  space=False title=False ident=False
'²'            alpha=False decimal=False digit=True  numeric=True  alnum=True  space=False title=False ident=False

split, rsplit, splitlines, partition, rpartition and join

Python
csv = "asha,24,Pune,India"
print(csv.split(","))
print(csv.split(",", 1))
print(csv.rsplit(",", 1))
print("  many   spaces here ".split())
print("line1\nline2\r\nline3".splitlines())
print("user@webnest.in".partition("@"))
print("archive.tar.gz".rpartition("."))
print(" | ".join(["Python", "Java", "SQL"]))
print("-".join("2026"))
Output
['asha', '24', 'Pune', 'India']
['asha', '24,Pune,India']
['asha,24,Pune', 'India']
['many', 'spaces', 'here']
['line1', 'line2', 'line3']
('user', '@', 'webnest.in')
('archive.tar', '.', 'gz')
Python | Java | SQL
2-0-2-6

Trimming, prefixes, padding and alignment

Python
raw = "   hello world   "
print(repr(raw.strip()), repr(raw.lstrip()), repr(raw.rstrip()))
print("xxhixx".strip("x"))
print("INV-1042".removeprefix("INV-"), "report.pdf".removesuffix(".pdf"))
print("[" + "Menu".center(12, "*") + "]")
print("[" + "Left".ljust(8) + "]", "[" + "Right".rjust(8) + "]")
print("42".zfill(5), "-42".zfill(5))
print(repr("a\tb".expandtabs(4)))
Output
'hello world' 'hello world   ' '   hello world'
hi
1042 report
[****Menu****]
[Left    ] [   Right]
00042 -0042
'a   b'

replace, translate, encode and format

Python
msg = "I like Java. Java is great."
print(msg.replace("Java", "Python"))
print(msg.replace("Java", "Python", 1))

table = str.maketrans("aeiou", "AEIOU", "!?")
print("hello world!?".translate(table))

data = "₹500".encode("utf-8")
print(data, data.decode("utf-8"))
print("{} scored {:.1f}%".format("Asha", 91.456))
print("{name} is {age}".format_map({"name": "Ravi", "age": 30}))
print("Hello\tWorld".isprintable(), "abc".isascii(), "café".isascii())
Output
I like Python. Python is great.
I like Python. Java is great.
hEllO wOrld
b'\xe2\x82\xb9500' ₹500
Asha scored 91.5%
Ravi is 30
False True False

Common Mistakes

  • Calling s.upper() and expecting s to change — strings are immutable; assign the result.
  • Using find() and forgetting it returns -1 (which is a valid negative index!) when not found.
  • Using isdigit() to validate that text is a normal integer; isdecimal() is stricter, and int() in try/except is safest.
  • Using strip("abc") expecting to remove the substring "abc" — it removes any of those characters; use removeprefix/removesuffix.
  • Building strings in a loop with += instead of collecting parts and using join().

Key Points to Remember

  • Every string method returns a new string; the original is unchanged.
  • Case: upper, lower, capitalize, title, swapcase, casefold.
  • Search: find/rfind (-1), index/rindex (ValueError), count, startswith, endswith.
  • Tests: isalpha, isdigit, isdecimal, isnumeric, isalnum, isspace, istitle, isidentifier...
  • split/rsplit/splitlines/partition break text; join combines; strip/pad/zfill/replace/translate transform it.

Practice the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.