String Methods

String methods let you check text or make a changed copy of it. Here are some common ones.

MethodWhat it does
strip()Removes spaces and other whitespace at both ends
upper() / lower()Makes all letters uppercase or lowercase
replace(old, new)Replaces matching text
count(text)Counts how many times the text appears
startswith(text)Checks if the string starts with the text
endswith(text)Checks if the string ends with the text
raw_code = "  inv_204  "
code = raw_code.strip().upper()

print(code)
print(code.startswith("INV_"))
print(code.replace("INV_", "ORDER-"))
print(code.count("0"))
print("204" in code)
print("inv" in code)

Output:

INV_204
True
ORDER-204
1
True
False

strip removes the spaces around the code, and upper makes every letter uppercase. Strings are immutable, which means they cannot be changed. So these methods return a new string, and the original text stays the same. To keep the result, assign it to a variable, like code here.

count("0") counts how many times "0" appears in the code. The expression "204" in code checks if "204" appears anywhere inside code. It gives True or False.

The last line prints False because searches are case-sensitive. This means uppercase and lowercase letters count as different. The code is now uppercase, and "inv" is lowercase. When case should not matter, change both sides to lowercase with lower before you compare.

In the exercise, make a word uppercase, count and search its letters, and replace some of them.