String Methods

Programs spend much of their time tidying and searching text: trimming stray spaces from user input, checking whether an email contains @, or treating "yes", "Yes" and "YES" as the same answer. Python strings come with built-in tools for these jobs. This lesson shows how to call them, what each kind returns, and the rule that trips up almost every beginner.

Calling a method and using its result

A string method is a function that belongs to a string and is called with dot notation: the string, a dot, the method name, then parentheses holding any arguments.


Python
word = "banana"
n = word.count("a")    # 3
loud = word.upper()    # "BANANA"


Every call produces a return value that you can store, print or use inside a larger expression. Python strings are immutable, so upper() builds and returns a brand-new string and the original string never changes. After the code above, word is still "banana".



When a method returns a string, you can call another string method on that result. These chained calls run left to right: " Hi ".strip().lower() first strips to "Hi", then lowercases that to "hi".

Methods that search

Searching methods report on a string without altering it. Positions are indices, and counting starts at 0.

  • find(sub) returns the index where sub first begins, or -1 if sub never appears. An optional second argument, as in find(sub, start), begins the search at index start.
  • index(sub) gives the same position but raises a ValueError instead of returning -1.
  • count(sub) returns how many non-overlapping times sub occurs.
  • startswith(prefix) and endswith(suffix) return True or False.

Example: With word = "banana", word.find("an") is 1, because the first "an" starts at index 1. word.find("an", 2) is 3, because the search begins at index 2. word.count("ana") is 1, not 2: the two copies of "ana" overlap, and count resumes searching after the end of each match.


Every search is case-sensitive. "Ottawa".find("o") is -1, because the only O in the word is a capital.



Methods that transform, split and join text

strip(), lower(), upper() and replace() return strings, while split() returns a list of strings. join() combines strings into a single string. None changes the original string. Each row below that uses s starts from s = " Go Team ", which has two spaces at each end.


Call

What it returns

Result

s.strip()

copy with whitespace removed from both ends

"Go Team"

s.lower()

copy with every letter in lowercase

" go team "

s.upper()

copy with every letter in uppercase

" GO TEAM "

s.replace("Team", "Bears")

copy with every match of the first argument swapped for the second

" Go Bears "

s.split()

list of the words between runs of whitespace

["Go", "Team"]

"-".join(["Go", "Team"])

the list items glued together with the separator

"Go-Team"


lstrip() and rstrip() trim only the left or right end. split() with no argument ignores leading and trailing whitespace, while split(",") cuts at every comma exactly and keeps any spaces that sit beside the commas. Note that join is called on the separator, not on the list.


If you also write Java, the same ideas appear as indexOf, toUpperCase and trim, and Java strings are immutable too.

What to remember

  • Call a method with dot notation; it returns a value you must store or use.
  • Strings are immutable: methods leave the original string unchanged. Methods such as upper() return strings; split() returns a list of strings.
  • find returns -1 when the target is absent; index raises an error.
  • count counts non-overlapping matches, and all searches are case-sensitive.
  • Chained calls run left to right, each acting on the previous result.

Example: Cleaning an address field

A sign-up form saves exactly what the user typed, stray spaces included. One record arrives as:


Python
raw = "  Maple Street, Toronto, ON  "


The string has two spaces before Maple and two after ON. Work each part before revealing its solution.


a) Store cleaned = raw.strip(). What does cleaned.find(",") return?


Count the characters first: raw holds ________ characters. strip() removes the two leading and two trailing spaces but leaves the spaces inside the text, so cleaned is "Maple Street, Toronto, ON" with ________ characters.


Now index cleaned from 0. Maple occupies indices 0 to 4, the space is index 5, Street occupies 6 to 11, and the first comma follows at index 12. find stops at the first match, so the later comma is ignored.


cleaned.find(",") returns 12. Searching raw instead would give 14, because the two leading spaces shift every position by 2.


b) Split the fields with parts = cleaned.split(", ") and store the city in a variable city.


split(", ") cuts at each comma followed by a space and drops the separator itself. Everything before the first comma at index 12 becomes the first piece, "________", and the remaining pieces are "Toronto" and "ON".


The city is the second piece. Lists also count from 0, so it sits at list index ________, and city = parts[1] stores "Toronto".


Had you written split(",") with no space, the second piece would be " Toronto" with a leading space, and a comparison such as city == "Toronto" would fail.


c) Compare cleaned.count("O") with cleaned.upper().count("O").


count is case-sensitive. In cleaned, every letter of Toronto after the T is lowercase, so the only capital O is the one in ON. Therefore cleaned.count("O") is 1.


In the chained call, cleaned.upper() runs first and returns "________". In that new string TORONTO contributes ________ capital O's and ON contributes one more, so cleaned.upper().count("O") is 4.


Calling upper() did not change cleaned; a second cleaned.count("O") would still return 1.


d) Abbreviate the street with short = cleaned.replace("Street", "St."). What is len(short)?


replace returns a copy in which each occurrence of "Street" becomes "St.", so short is "________".


The swap replaces 6 characters with 3, a net loss of 3, so


len(short)=25−3=22\text{len(short)} = 25 - 3 = 22


Counting directly agrees: Maple St., is 10 characters, the space and Toronto, bring it to 19, and the space and ON bring it to 22. So len(short) is 22.

Match each Python string method with a description of the value it returns when it is called on a string such as "Hello, world".

Match each term
A.

A copy in which each occurrence of one substring is swapped for another

B.

The starting position of a substring, or -1 when it is absent

C.

The starting position of a substring, but raises an error when it is absent

D.

A copy with every lowercase letter converted to a capital

E.

A list of the pieces between occurrences of a separator

F.

How many non-overlapping times a substring occurs

G.

A copy with whitespace removed from both ends

split()

count()

replace()

index()

find()

upper()

strip()

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A laboratory program extracts sections of a sample identifier using the following Python code. Complete the table with the number of characters in each result. Enter exact integers.


Python
tag = "BIO-7392"
a = tag[0:3]
b = tag[-4:]
c = tag[4:7]
d = tag[::2]
e = tag[6:3]
f = tag[4:30]
ResultNumber of characters
a
b
c
d
e
f

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A program normalizes an email address before checking it:


Python
email = "  Priya.Shah@school.ca "
user = email.strip().lower()
pos = user.find("@")


The string assigned to email has two spaces before P and one space after ca. What value does pos hold after these lines run? Give your answer as an integer.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice