Skip to content
Theory · Strings · lesson 5 of 10

String methods

Let's go back to the rack of tiles, only now the tiles on it are glued down. You can look at them and name them by number, but you cannot take one off or swap it. To get a different word, you set up a new rack next to it with the tiles you need.

The variable name here is a tag, as in the theme about variables. The tag can be moved to a new rack, and the old rack stays exactly as it was.

This is how strings work in Python. A character of a string can be read by its index, but it cannot be replaced that way. An attempt to write a new character into a string stops the program:

Python
name = "anna"
print(name)  # anna
name[0] = "A"  # ✗
print(name)
TEXT
TypeError: 'str' object does not support item assignment

Let's go through what happens here:

  1. The first print gets to print anna.
  2. The check before the run does not find this error: it comes up when the assignment line runs.
  3. The program stops at name[0] = "A", and the second print does not run.

Immutable strings

Strings in Python are immutable: a string, once created, cannot be changed, neither as a whole nor one character at a time. Instead, you build a new string and bind the name to it. After name = "A" + name[1:], the name name refers to "Anna".

The string "anna" itself does not change—only what name refers to changes. The tag was moved to a new rack, and the old rack stayed as it was.

Interviewers like to ask this: "Can you change a string in Python?" The answer:

  • no, strings are immutable, and s[0] = "x" raises a TypeError;
  • methods and slices return a new string;
  • to make a name refer to the result, assign it: s = s.upper().

Methods

A method is a function that belongs to a value and is called through a dot: text.upper(). String methods do not change the string; they return a new string, a number or True/False. Here are four methods that build a new string:

  • upper() and lower()—all letters uppercase or lowercase;
  • strip()—the string without spaces at its edges;
  • replace(old, new)—every occurrence of old replaced with new.
Python
text = "  Hello, World  "
clean = text.strip()
print(clean.upper(), clean.lower())  # HELLO, WORLD hello, world
print(clean.replace("World", "Anna"))  # Hello, Anna
print(len(text), len(clean))  # 16 12

Let's go through the example line by line:

  1. text.strip() returns the string without spaces at its edges, and it is bound to clean.
  2. upper and lower print HELLO, WORLD and hello, world.
  3. replace replaces World with Anna. It replaces every occurrence, not only the first: "a-b-c".replace("-", "") gives abc.
  4. The length of text is still 16 after all the calls: no method changed it.

Calls can be chained: text.strip().lower() first removes the spaces and then changes the case of the result.

A new string, not the old

Every method and every slice builds a new string, and s stays the same until you assign the result to it. Press "Next step" and watch s: it changes only on the line s = s.upper().

LiveA method builds a new stringstep 1 of 9 · frames: 1

The name s is bound to the string 'lemon'.

Watch s: it changes only after an assignment

The rule is this: store the result of a method or a slice—in a new variable or, with =, in the same one. A call without an assignment, like s.replace("l", "m") on the fourth line, builds a string and loses it at once.

Searching and counting

Other methods build no string but answer a question about it:

  • find(sub)—the index of the first occurrence of sub, or -1 if there is none;
  • count(sub)—how many times sub occurs in the string;
  • startswith(prefix) and endswith(suffix)—whether the string starts with prefix and whether it ends with suffix.
Python
s = "banana"
print(s.find("an"), s.find("x"))  # 1 -1
print(s.count("a"), s.count("an"))  # 3 2
print(s.startswith("ba"), s.endswith("na"))  # True True

find and count, like the in operator, tell letter case apart: "Banana".count("b") is 0. To keep case out of the way, the string is first brought to one case, such as s.lower().count("b").

Common mistake

A method is called, but its result is not stored anywhere:

Python
name = "anna"
name.upper()  # ✗
print(name)  # anna

There is no error, but anna is printed. upper returned a new string, ANNA, but it went neither into a variable nor into print, and was lost. name itself did not change, because strings are immutable. Assign the result: name = name.upper().

Key points

  • Strings are immutable: s[0] = "A" raises a TypeError.
  • Methods and slices return a new string, and the original stays the same.
  • To keep the result, assign it: s = s.upper().
  • find, count, startswith, endswith and in tell letter case apart.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way