String methods

Part of the free LogicWiz Python course, Module 4: Strings. The examples and practice run in the app.

Meher's sign-up form saved ' [email protected] ' with spaces and capitals, so Riya's login failed every time. Two methods, strip() and lower(), fix it, but only if you keep what they return.

You'll learn to

  • Search text with `find`, `index`, `count` and `in`
  • Break and join text with `split`, `join` and `partition`
  • Clean text with `strip`, `replace` and the case methods
  • Test text with `isalpha`, `isdigit`, `isupper` and friends

Learn

Methods give back a new string

A method is a function that belongs to a value, called with a dot: email.lower().

Strings are immutable, so string methods never change the original. They return a new string. If you don't save it, it is lost:

  • email.lower() alone does nothing useful
  • email = email.lower() keeps the result

Fixing Riya's login

email = "  [email protected]  "
email.strip()
print("[" + email + "]")

email = email.strip().lower()
print("[" + email + "]")

The first strip() result is thrown away. The second line chains two methods: strip first, then lower the result, then save it.

find vs index

s.find(x)s.index(x)
Returns the first position of xReturns the first position of x
Not found: returns -1Not found: ValueError (crash)
Use it to check and then actUse it when x must be there
s.find(x, 5) starts looking at index 5s.index(x, 5) the same

Searching and replacing

s = "chai, samosa, chai, poha"
print(s.find("chai"), s.find("chai", 1), s.find("idli"))
print(s.count("chai"))
print("poha" in s, "idli" in s)
print(s.index("samosa"))
print(s.replace("chai", "coffee"))
print(s.replace("chai", "coffee", 1))

replace(old, new, 1) changes only the first match. in is the simplest yes/no check.

split, join, partition

order = "chai,samosa,vada pav"
items = order.split(",")
print(items, len(items))
print(" | ".join(items))

print("Aarav   Kumar Sharma".split())
print("[email protected]".partition("@"))
print("no-at-sign".partition("@"))

split(",") cuts at each comma and gives a list of pieces. split() with nothing cuts at any run of spaces. "sep".join(pieces) glues them back. partition always returns 3 parts: before, the separator, after (with empty strings if the separator is missing).

Case and checks

name = "meher KAPOOR"
print(name.upper(), "|", name.lower())
print(name.title(), "|", name.capitalize(), "|", name.swapcase())
print("2026".isdigit(), "Riya".isalpha(), "Riya1".isalnum())
print("Riya Sen".isalpha(), "-5".isdigit(), "3.5".isdigit())
print("ABC".isupper(), "abc".islower(), "   ".isspace())

title() capitalises every word; capitalize() only the first letter of the whole string, and lowers the rest.

isalpha() is False if there is any space: "Riya Sen".isalpha() is False. isdigit() is False for "-5" and "3.5" (the - and . aren't digits). All is… methods are False for the empty string "".

More trimming

print("***Rs 50***".strip("*"))
print("00042".lstrip("0"))
print("Hello!!!".rstrip("!"))
print("report.txt".endswith(".txt"), "9876".startswith("98"))

CBSE output questions mix these: split vs partition (partition gives a tuple of 3), title vs capitalize, find returning -1. Error-finding questions use s.index("z") (ValueError) or s[0] = "x" (TypeError). Write the result type too: split gives a list […], partition a tuple (…).

In one line

Methods return a new string (save it!); find gives -1 but index crashes; split → list, "sep".join(list) → string, partition → 3-tuple.