Sub topic 1
Python String Methods for Searching and Changing Text
Prerequisites
Assume you know Python variables, function calls, string literals, indexing, lists, tuples, if statements, and for loops.
Strings are immutable: methods return new strings
A string is immutable, which means its characters cannot be changed in place. String methods therefore return a new string. The original remains unchanged.
s = "abc"
t = s.upper()
print(s) # abc
print(t) # ABCAssign the returned value when you need to keep the change. An expression such as s.upper() computes a result, but does not update s.
Checking whether text contains a substring
A substring is a smaller string inside another string. Use in for a Boolean answer:
message = "Hello, World"
print("World" in message) # True
print("world" in message) # FalseThe test is case-sensitive. Normalize both values first when the distinction is not important.
Finding where a substring occurs
Use find when you need a position. Positions are zero-based, and find returns -1 when the substring is absent. It accepts an optional starting position.
s = "Hello, World"
print(s.find("o")) # 4
print(s.find("o", 5)) # 8
print(s.find("xyz")) # -1rfind searches from the right and returns the last matching position. index and rindex have similar behavior, but raise ValueError if no match exists.
try:
"Hello".index("x")
except ValueError:
print("not found")Counting occurrences
count returns the number of non-overlapping occurrences. An empty match has special behavior, so count meaningful substrings instead.
print("banana".count("an")) # 2
print("aaaa".count("aa")) # 2The second result is 2, not 3, because the matches cannot overlap.
Exercise
Which method should you use to test whether "cat" occurs in text without needing its position?
Show answer
Use "cat" in text, which returns True or False.