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:
name = "anna"
print(name) # anna
name[0] = "A" # ✗
print(name)TypeError: 'str' object does not support item assignmentLet's go through what happens here:
- The first
printgets to printanna. - The check before the run does not find this error: it comes up when the assignment line runs.
- The program stops at
name[0] = "A", and the secondprintdoes 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 aTypeError; - 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()andlower()—all letters uppercase or lowercase;strip()—the string without spaces at its edges;replace(old, new)—every occurrence ofoldreplaced withnew.
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 12Let's go through the example line by line:
text.strip()returns the string without spaces at its edges, and it is bound toclean.upperandlowerprintHELLO, WORLDandhello, world.replacereplacesWorldwithAnna. It replaces every occurrence, not only the first:"a-b-c".replace("-", "")givesabc.- The length of
textis still16after 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().
1s = "lemon"2t = s.upper()3print(s, t)4s.replace("l", "m")5print(s)6u = s[1:]7print(s, u)8s = s.upper()9print(s, t)
The name s is bound to the string 'lemon'.
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 ofsub, or-1if there is none;count(sub)—how many timessuboccurs in the string;startswith(prefix)andendswith(suffix)—whether the string starts withprefixand whether it ends withsuffix.
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 Truefind 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:
name = "anna"
name.upper() # ✗
print(name) # annaThere 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 aTypeError. - 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,endswithandintell 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.